From fbd56b0ecced359f8239f737a6dfad1a72eb6001 Mon Sep 17 00:00:00 2001 From: Simon Giesecke Date: Wed, 1 Jul 2020 08:29:29 +0000 Subject: [PATCH] Bug 1648010 - Replace uses of NS_LITERAL_STRING/NS_LITERAL_CSTRING macros by _ns literals. r=geckoview-reviewers,jgilbert,agi,hsivonen,froydnj Differential Revision: https://phabricator.services.mozilla.com/D80860 --- accessible/android/AccessibleWrap.cpp | 21 +- accessible/aom/AccessibleNode.cpp | 2 +- accessible/atk/Platform.cpp | 7 +- accessible/base/ARIAMap.cpp | 3 +- accessible/base/DocManager.cpp | 9 +- accessible/base/MarkupMap.h | 3 +- accessible/base/TextAttrs.cpp | 25 +- accessible/base/XULMap.h | 2 +- accessible/base/nsAccUtils.cpp | 7 +- accessible/base/nsAccessibilityService.cpp | 103 +- accessible/base/nsEventShell.cpp | 3 +- accessible/generic/ARIAGridAccessible.cpp | 16 +- accessible/generic/Accessible.cpp | 30 +- accessible/generic/DocAccessible.cpp | 3 +- accessible/generic/HyperTextAccessible.cpp | 6 +- accessible/generic/RootAccessible.cpp | 12 +- accessible/generic/TableAccessible.cpp | 23 +- accessible/html/HTMLFormControlAccessible.cpp | 3 +- accessible/html/HTMLFormControlAccessible.h | 2 +- accessible/html/HTMLSelectAccessible.cpp | 2 +- accessible/html/HTMLTableAccessible.cpp | 6 +- accessible/mac/mozAccessible.mm | 63 +- accessible/mac/mozSelectableElements.mm | 2 +- accessible/windows/msaa/AccessibleWrap.cpp | 2 +- .../msaa/ApplicationAccessibleWrap.cpp | 4 +- accessible/windows/msaa/Compatibility.cpp | 5 +- accessible/windows/msaa/CompatibilityUIA.cpp | 5 +- accessible/windows/msaa/Platform.cpp | 4 +- .../windows/msaa/XULMenuAccessibleWrap.cpp | 2 +- accessible/windows/uia/uiaRawElmProvider.cpp | 2 +- accessible/xul/XULTabAccessible.cpp | 3 +- accessible/xul/XULTreeAccessible.cpp | 5 +- accessible/xul/XULTreeGridAccessible.cpp | 6 +- .../dirprovider/DirectoryProvider.cpp | 6 +- .../migration/nsIEHistoryEnumerator.cpp | 7 +- .../components/shell/nsGNOMEShellService.cpp | 16 +- .../components/shell/nsMacShellService.cpp | 5 +- .../shell/nsWindowsShellService.cpp | 35 +- caps/BasePrincipal.cpp | 10 +- caps/ContentPrincipal.cpp | 2 +- caps/NullPrincipal.cpp | 2 +- caps/NullPrincipalURI.cpp | 6 +- caps/OriginAttributes.cpp | 16 +- caps/SystemPrincipal.cpp | 2 +- caps/nsScriptSecurityManager.cpp | 27 +- .../gtest/TestPrincipalSerialization.cpp | 8 +- chrome/nsChromeProtocolHandler.cpp | 4 +- chrome/nsChromeRegistryChrome.cpp | 13 +- docshell/base/BrowsingContext.cpp | 8 +- docshell/base/CanonicalBrowsingContext.cpp | 10 +- docshell/base/nsDocShell.cpp | 63 +- docshell/base/nsDocShellTreeOwner.cpp | 36 +- docshell/base/nsPingListener.cpp | 22 +- docshell/shistory/nsSHistory.cpp | 20 +- dom/abort/AbortSignal.cpp | 3 +- dom/animation/Animation.cpp | 9 +- dom/animation/KeyframeEffect.cpp | 2 +- dom/animation/KeyframeUtils.cpp | 6 +- dom/base/AnonymousContent.cpp | 5 +- dom/base/BodyUtil.cpp | 8 +- dom/base/ChromeUtils.cpp | 5 +- dom/base/CustomElementRegistry.cpp | 8 +- dom/base/DOMException.cpp | 2 +- dom/base/DOMImplementation.cpp | 16 +- dom/base/DOMParser.cpp | 3 +- dom/base/DOMRequest.cpp | 8 +- dom/base/DocGroup.cpp | 3 +- dom/base/Document.cpp | 297 ++- dom/base/Element.cpp | 18 +- dom/base/EventSource.cpp | 29 +- dom/base/FormData.cpp | 2 +- dom/base/FullscreenChange.h | 6 +- dom/base/ImageEncoder.cpp | 2 +- .../InProcessBrowserChildMessageManager.cpp | 2 +- dom/base/MaybeCrossOriginObject.cpp | 8 +- dom/base/Navigator.cpp | 50 +- dom/base/NodeInfo.cpp | 3 +- dom/base/PopupBlocker.cpp | 2 +- dom/base/PostMessageEvent.cpp | 6 +- dom/base/RemoteOuterWindowProxy.cpp | 2 +- dom/base/ScreenOrientation.cpp | 20 +- dom/base/Selection.cpp | 8 +- dom/base/ShadowRoot.h | 2 +- dom/base/StorageAccessPermissionRequest.cpp | 4 +- dom/base/WindowOrientationObserver.cpp | 3 +- dom/base/XPathGenerator.cpp | 20 +- dom/base/nsAttrValue.cpp | 2 +- dom/base/nsContentAreaDragDrop.cpp | 13 +- dom/base/nsContentSink.cpp | 13 +- dom/base/nsContentUtils.cpp | 79 +- dom/base/nsCopySupport.cpp | 2 +- dom/base/nsDOMDataChannel.cpp | 8 +- dom/base/nsDOMSerializer.cpp | 2 +- dom/base/nsFocusManager.cpp | 36 +- dom/base/nsFrameLoader.cpp | 18 +- dom/base/nsFrameLoaderOwner.cpp | 6 +- dom/base/nsFrameMessageManager.cpp | 19 +- dom/base/nsGlobalWindowInner.cpp | 35 +- dom/base/nsGlobalWindowOuter.cpp | 56 +- dom/base/nsHTMLContentSerializer.cpp | 7 +- dom/base/nsINode.cpp | 14 +- dom/base/nsImageLoadingContent.cpp | 30 +- dom/base/nsJSEnvironment.cpp | 7 +- dom/base/nsObjectLoadingContent.cpp | 58 +- dom/base/nsPlainTextSerializer.cpp | 29 +- dom/base/nsPluginArray.cpp | 4 +- dom/base/nsSyncLoadService.cpp | 8 +- dom/base/nsTreeSanitizer.cpp | 8 +- dom/base/nsWindowMemoryReporter.cpp | 51 +- dom/base/nsXHTMLContentSerializer.cpp | 34 +- dom/base/nsXMLContentSerializer.cpp | 45 +- dom/base/nsXMLContentSerializer.h | 4 +- dom/base/test/gtest/TestContentUtils.cpp | 55 +- dom/base/test/gtest/TestMimeType.cpp | 164 +- dom/base/test/gtest/TestParser.cpp | 4 +- dom/battery/BatteryManager.cpp | 9 +- dom/bindings/BindingUtils.cpp | 7 +- dom/bindings/Codegen.py | 2 +- dom/bindings/RemoteObjectProxy.cpp | 4 +- dom/bindings/nsScriptErrorWithStack.cpp | 2 +- .../test/TestInterfaceIterableDouble.cpp | 9 +- .../test/TestInterfaceIterableDoubleUnion.cpp | 7 +- dom/broadcastchannel/BroadcastChannel.cpp | 8 +- dom/cache/AutoUtils.cpp | 2 +- dom/cache/CacheOpParent.cpp | 3 +- dom/cache/DBAction.cpp | 12 +- dom/cache/DBSchema.cpp | 753 ++++---- dom/cache/FileUtils.cpp | 12 +- dom/cache/FileUtilsImpl.h | 8 +- dom/cache/Manager.cpp | 2 +- dom/cache/QuotaClient.cpp | 3 +- dom/cache/TypeUtils.cpp | 4 +- dom/canvas/CanvasRenderingContext2D.cpp | 4 +- dom/canvas/CanvasUtils.cpp | 11 +- dom/canvas/ClientWebGLContext.cpp | 11 +- dom/canvas/ImageBitmap.cpp | 2 +- dom/canvas/QueueParamTraits.h | 6 +- dom/canvas/WebGLContext.cpp | 23 +- dom/canvas/XRWebGLLayer.cpp | 18 +- dom/clients/manager/ClientManagerService.cpp | 10 +- dom/clients/manager/ClientSource.cpp | 32 +- dom/console/Console.cpp | 35 +- dom/console/ConsoleInstance.cpp | 31 +- dom/console/ConsoleUtils.cpp | 10 +- dom/events/ContentEventHandler.cpp | 2 +- dom/events/DataTransfer.cpp | 22 +- dom/events/DataTransferItem.h | 6 +- dom/events/DataTransferItemList.cpp | 2 +- dom/events/Event.cpp | 5 +- dom/events/EventListenerManager.cpp | 8 +- dom/events/EventTarget.cpp | 2 +- dom/events/GlobalKeyListener.cpp | 92 +- dom/events/KeyEventHandler.cpp | 2 +- dom/events/NotifyPaintEvent.cpp | 2 +- dom/events/PendingFullscreenEvent.h | 4 +- dom/events/PointerEventHandler.cpp | 4 +- dom/events/ScrollAreaEvent.cpp | 2 +- dom/events/TextComposition.cpp | 2 +- dom/events/UIEvent.cpp | 2 +- dom/events/WheelHandlingHelper.cpp | 5 +- dom/fetch/BodyExtractor.cpp | 3 +- dom/fetch/Fetch.cpp | 2 +- dom/fetch/FetchDriver.cpp | 31 +- dom/fetch/FetchObserver.cpp | 3 +- dom/fetch/FetchStreamReader.cpp | 9 +- dom/fetch/FetchUtil.cpp | 5 +- dom/fetch/InternalHeaders.cpp | 7 +- dom/fetch/InternalResponse.h | 2 +- dom/fetch/Request.cpp | 12 +- dom/fetch/Response.cpp | 9 +- dom/file/BaseBlobImpl.h | 2 +- dom/file/EmptyBlobImpl.h | 2 +- dom/file/FileBlobImpl.cpp | 5 +- dom/file/FileReader.cpp | 2 +- dom/file/MemoryBlobImpl.cpp | 7 +- dom/file/MemoryBlobImpl.h | 2 +- dom/file/StringBlobImpl.h | 2 +- dom/file/TemporaryFileBlobImpl.h | 2 +- dom/file/ipc/RemoteLazyInputStreamStorage.cpp | 2 +- dom/file/uri/BlobURLProtocolHandler.cpp | 2 +- dom/filehandle/ActorsParent.cpp | 2 +- dom/filesystem/FileSystemSecurity.cpp | 7 +- dom/gamepad/GamepadManager.cpp | 12 +- dom/geolocation/Geolocation.cpp | 7 +- dom/geolocation/GeolocationPositionError.cpp | 6 +- dom/html/HTMLAllCollection.cpp | 2 +- dom/html/HTMLAudioElement.cpp | 4 +- dom/html/HTMLCanvasElement.cpp | 14 +- dom/html/HTMLDetailsElement.cpp | 4 +- dom/html/HTMLDialogElement.cpp | 10 +- dom/html/HTMLFormElement.cpp | 22 +- dom/html/HTMLFormSubmission.cpp | 49 +- dom/html/HTMLFormSubmission.h | 3 +- dom/html/HTMLIFrameElement.cpp | 4 +- dom/html/HTMLInputElement.cpp | 91 +- dom/html/HTMLLinkElement.cpp | 12 +- dom/html/HTMLMarqueeElement.cpp | 4 +- dom/html/HTMLMediaElement.cpp | 153 +- dom/html/HTMLMetaElement.cpp | 8 +- dom/html/HTMLScriptElement.cpp | 8 +- dom/html/HTMLSharedElement.cpp | 6 +- dom/html/HTMLSlotElement.cpp | 4 +- dom/html/HTMLTextAreaElement.cpp | 4 +- dom/html/HTMLTrackElement.cpp | 6 +- dom/html/HTMLVideoElement.cpp | 10 +- dom/html/ImageDocument.cpp | 51 +- dom/html/MediaDocument.cpp | 16 +- dom/html/MediaError.cpp | 4 +- dom/html/PluginDocument.cpp | 6 +- dom/html/TextControlState.cpp | 28 +- dom/html/TextTrackManager.cpp | 23 +- dom/html/VideoDocument.cpp | 15 +- dom/html/input/DateTimeInputTypes.cpp | 9 +- dom/html/nsDOMStringMap.cpp | 5 +- dom/html/nsGenericHTMLElement.cpp | 7 +- dom/html/nsGenericHTMLElement.h | 18 +- dom/html/nsIConstraintValidation.cpp | 12 +- dom/indexedDB/ActorsParent.cpp | 1606 ++++++++--------- dom/indexedDB/IDBDatabase.cpp | 5 +- dom/indexedDB/IDBFileRequest.cpp | 2 +- dom/indexedDB/PermissionRequestBase.cpp | 2 +- dom/indexedDB/test/gtest/TestKey.cpp | 40 +- dom/ipc/BrowserChild.cpp | 3 +- dom/ipc/BrowserParent.cpp | 26 +- dom/ipc/ContentChild.cpp | 25 +- dom/ipc/ContentParent.cpp | 94 +- dom/ipc/ContentParent.h | 3 +- dom/ipc/JSActor.cpp | 7 +- dom/ipc/PreallocatedProcessManager.cpp | 6 +- dom/ipc/ProcessActor.cpp | 5 +- dom/ipc/ProcessHangMonitor.cpp | 6 +- dom/ipc/ProcessPriorityManager.cpp | 15 +- dom/ipc/SharedMap.cpp | 4 +- dom/ipc/WindowGlobalActor.cpp | 5 +- dom/ipc/WindowGlobalChild.cpp | 2 +- dom/ipc/WindowGlobalParent.cpp | 2 +- dom/jsurl/nsJSProtocolHandler.cpp | 9 +- dom/l10n/DOMLocalization.cpp | 56 +- dom/l10n/tests/gtest/TestL10nOverlays.cpp | 6 +- dom/localstorage/ActorsParent.cpp | 266 ++- dom/mathml/MathMLElement.cpp | 11 +- dom/media/ADTSDecoder.cpp | 4 +- dom/media/AutoplayPolicy.cpp | 13 +- ...kgroundVideoDecodingPermissionObserver.cpp | 12 +- dom/media/Benchmark.cpp | 3 +- dom/media/ChannelMediaResource.cpp | 18 +- dom/media/DOMMediaStream.cpp | 4 +- dom/media/GVAutoplayPermissionRequest.cpp | 11 +- dom/media/GraphDriver.cpp | 3 +- dom/media/MediaDecoder.cpp | 26 +- dom/media/MediaDecoderStateMachine.cpp | 4 +- dom/media/MediaDevices.cpp | 2 +- dom/media/MediaFormatReader.cpp | 2 +- dom/media/MediaInfo.h | 10 +- dom/media/MediaMIMETypes.cpp | 2 +- dom/media/MediaManager.cpp | 113 +- dom/media/MediaManager.h | 2 +- dom/media/MediaRecorder.cpp | 43 +- dom/media/MediaShutdownManager.cpp | 4 +- dom/media/MediaStreamTrack.cpp | 7 +- dom/media/MediaTimer.cpp | 2 +- dom/media/MediaTrackGraph.cpp | 6 +- dom/media/MediaTrackList.cpp | 8 +- dom/media/TextTrackList.cpp | 6 +- dom/media/VideoUtils.h | 2 +- dom/media/WebVTTListener.cpp | 2 +- dom/media/doctor/DecoderDoctorDiagnostics.cpp | 32 +- dom/media/eme/EMEUtils.cpp | 4 +- dom/media/eme/MediaEncryptedEvent.cpp | 4 +- dom/media/eme/MediaKeyError.cpp | 2 +- dom/media/eme/MediaKeyMessageEvent.cpp | 2 +- dom/media/eme/MediaKeySession.cpp | 18 +- dom/media/eme/MediaKeySystemAccess.cpp | 39 +- dom/media/eme/MediaKeySystemAccessManager.cpp | 35 +- .../MediaKeySystemAccessPermissionRequest.cpp | 7 +- dom/media/eme/MediaKeys.cpp | 7 +- dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp | 27 +- dom/media/encoder/OpusTrackEncoder.cpp | 2 +- dom/media/flac/FlacDecoder.cpp | 2 +- dom/media/gmp/ChromiumCDMParent.cpp | 28 +- dom/media/gmp/ChromiumCDMProxy.cpp | 32 +- dom/media/gmp/GMPChild.cpp | 36 +- dom/media/gmp/GMPDiskStorage.cpp | 2 +- dom/media/gmp/GMPParent.cpp | 50 +- dom/media/gmp/GMPService.cpp | 11 +- dom/media/gmp/GMPServiceChild.cpp | 4 +- dom/media/gmp/GMPServiceParent.cpp | 49 +- dom/media/gmp/GMPVideoDecoderParent.cpp | 4 +- dom/media/gtest/TestAudioDeviceEnumerator.cpp | 2 +- dom/media/gtest/TestCDMStorage.cpp | 133 +- dom/media/gtest/TestDecoderBenchmark.cpp | 44 +- dom/media/gtest/TestGMPCrossOrigin.cpp | 22 +- dom/media/gtest/TestGMPRemoveAndDelete.cpp | 18 +- dom/media/gtest/TestGroupId.cpp | 137 +- dom/media/gtest/TestMediaDataEncoder.cpp | 16 +- dom/media/gtest/TestMediaMIMETypes.cpp | 86 +- dom/media/gtest/mp4_demuxer/TestParser.cpp | 6 +- dom/media/imagecapture/CaptureTask.cpp | 2 +- dom/media/imagecapture/ImageCapture.cpp | 6 +- dom/media/ipc/RDDProcessManager.cpp | 6 +- dom/media/ipc/RemoteMediaDataDecoder.cpp | 3 +- dom/media/ipc/RemoteMediaDataDecoder.h | 2 +- .../BenchmarkStorageParent.cpp | 5 +- .../mediacapabilities/DecoderBenchmark.cpp | 12 +- .../mediacapabilities/KeyValueStorage.cpp | 2 +- .../mediacapabilities/MediaCapabilities.cpp | 12 +- dom/media/mediacontrol/MediaController.cpp | 2 +- dom/media/mediacontrol/MediaStatusManager.cpp | 4 +- dom/media/mp3/MP3Decoder.cpp | 4 +- dom/media/mp4/DecoderData.cpp | 16 +- dom/media/mp4/Index.cpp | 10 +- dom/media/mp4/MP4Decoder.cpp | 17 +- dom/media/mp4/MP4Demuxer.cpp | 2 +- dom/media/ogg/OggCodecState.cpp | 6 +- dom/media/ogg/OggDecoder.cpp | 6 +- dom/media/ogg/OggDemuxer.cpp | 18 +- dom/media/platforms/agnostic/AOMDecoder.h | 2 +- .../platforms/agnostic/BlankDecoderModule.cpp | 6 +- dom/media/platforms/agnostic/DAV1DDecoder.h | 2 +- .../agnostic/DummyMediaDataDecoder.cpp | 2 +- .../platforms/agnostic/NullDecoderModule.cpp | 3 +- dom/media/platforms/agnostic/OpusDecoder.h | 2 +- dom/media/platforms/agnostic/TheoraDecoder.h | 2 +- dom/media/platforms/agnostic/VPXDecoder.h | 2 +- dom/media/platforms/agnostic/VorbisDecoder.h | 2 +- dom/media/platforms/agnostic/WAVDecoder.h | 2 +- .../agnostic/eme/ChromiumCDMVideoDecoder.cpp | 2 +- .../agnostic/gmp/GMPDecoderModule.cpp | 8 +- .../platforms/agnostic/gmp/GMPDecoderModule.h | 2 +- .../agnostic/gmp/GMPVideoDecoder.cpp | 6 +- .../platforms/agnostic/gmp/GMPVideoDecoder.h | 2 +- .../platforms/android/AndroidDataEncoder.h | 4 +- .../platforms/android/RemoteDataDecoder.cpp | 10 +- .../platforms/android/RemoteDataDecoder.h | 2 +- dom/media/platforms/apple/AppleATDecoder.h | 2 +- dom/media/platforms/apple/AppleVTDecoder.h | 5 +- dom/media/platforms/apple/AppleVTEncoder.h | 5 +- .../platforms/ffmpeg/FFmpegAudioDecoder.h | 2 +- .../platforms/ffmpeg/FFmpegVideoDecoder.h | 4 +- dom/media/platforms/omx/OmxDataDecoder.h | 4 +- dom/media/platforms/wmf/WMFAudioMFTManager.h | 2 +- dom/media/platforms/wmf/WMFMediaDataDecoder.h | 3 +- dom/media/platforms/wmf/WMFUtils.cpp | 2 +- .../platforms/wrappers/MediaChangeMonitor.h | 2 +- dom/media/systemservices/CamerasParent.cpp | 7 +- dom/media/systemservices/MediaParent.cpp | 2 +- dom/media/wave/WaveDecoder.cpp | 6 +- dom/media/wave/WaveDemuxer.cpp | 12 +- dom/media/webaudio/AudioBufferSourceNode.cpp | 2 +- dom/media/webaudio/AudioContext.cpp | 8 +- dom/media/webaudio/AudioDestinationNode.cpp | 7 +- dom/media/webaudio/AudioProcessingEvent.h | 3 +- .../webaudio/AudioWorkletGlobalScope.cpp | 17 +- dom/media/webaudio/AudioWorkletNode.cpp | 9 +- dom/media/webaudio/ConstantSourceNode.cpp | 2 +- dom/media/webaudio/MediaBufferDecoder.cpp | 6 +- .../webaudio/MediaStreamAudioSourceNode.cpp | 11 +- .../MediaStreamTrackAudioSourceNode.cpp | 11 +- dom/media/webaudio/OscillatorNode.cpp | 2 +- dom/media/webm/WebMDecoder.cpp | 9 +- dom/media/webm/WebMDemuxer.cpp | 6 +- dom/media/webrtc/MediaEngineDefault.cpp | 28 +- .../webrtc/MediaEngineRemoteVideoSource.cpp | 10 +- .../webrtc/MediaEngineTabVideoSource.cpp | 8 +- dom/media/webrtc/MediaEngineWebRTC.cpp | 10 +- dom/media/webrtc/MediaEngineWebRTCAudio.cpp | 6 +- dom/media/webrtc/MediaTrackConstraints.cpp | 6 +- dom/media/webrtc/RTCCertificate.cpp | 2 +- .../OnlineSpeechRecognitionService.cpp | 45 +- .../recognition/SpeechRecognition.cpp | 32 +- .../test/FakeSpeechRecognitionService.cpp | 4 +- dom/media/webspeech/synth/SpeechSynthesis.cpp | 2 +- .../synth/android/SpeechSynthesisService.cpp | 4 +- .../cocoa/OSXSpeechSynthesizerService.mm | 5 +- dom/media/webspeech/synth/nsSpeechTask.cpp | 29 +- .../webspeech/synth/nsSynthVoiceRegistry.cpp | 4 +- .../webspeech/synth/windows/SapiService.cpp | 13 +- dom/messagechannel/MessagePort.cpp | 8 +- dom/midi/MIDIAccess.cpp | 4 +- dom/midi/MIDIAccessManager.cpp | 2 +- dom/midi/MIDIMessageEvent.cpp | 2 +- dom/midi/MIDIPermissionRequest.cpp | 9 +- dom/midi/MIDIPort.cpp | 4 +- dom/midi/TestMIDIPlatformService.cpp | 45 +- dom/network/Connection.cpp | 2 +- dom/network/ConnectionWorker.cpp | 9 +- dom/network/TCPServerSocket.cpp | 6 +- dom/network/TCPSocket.cpp | 20 +- dom/network/TCPSocketParent.cpp | 8 +- dom/network/UDPSocket.cpp | 2 +- dom/network/UDPSocketParent.cpp | 4 +- dom/notification/Notification.cpp | 57 +- dom/notification/Notification.h | 6 +- dom/payments/BasicCardPayment.cpp | 19 +- dom/payments/PaymentActionResponse.cpp | 5 +- dom/payments/PaymentRequest.cpp | 28 +- dom/payments/PaymentRequestManager.cpp | 2 +- dom/payments/PaymentRequestService.cpp | 4 +- dom/payments/PaymentResponse.cpp | 2 +- dom/performance/Performance.cpp | 7 +- dom/performance/PerformanceMainThread.cpp | 2 +- dom/performance/PerformanceMark.cpp | 3 +- dom/performance/PerformanceMeasure.cpp | 2 +- dom/performance/PerformanceNavigationTiming.h | 4 +- dom/performance/PerformanceObserver.cpp | 6 +- dom/performance/PerformanceResourceTiming.cpp | 3 +- dom/performance/PerformanceTiming.cpp | 2 +- dom/permission/PermissionStatus.cpp | 8 +- dom/permission/PermissionUtils.cpp | 8 +- dom/plugins/base/PluginFinder.cpp | 14 +- dom/plugins/base/nsNPAPIPluginInstance.cpp | 3 +- .../base/nsPluginDirServiceProvider.cpp | 7 +- dom/plugins/base/nsPluginHost.cpp | 20 +- dom/plugins/base/nsPluginInstanceOwner.cpp | 131 +- .../base/nsPluginStreamListenerPeer.cpp | 4 +- dom/plugins/base/nsPluginsDirDarwin.cpp | 2 +- dom/plugins/base/nsPluginsDirWin.cpp | 8 +- dom/plugins/ipc/PluginHangUIParent.cpp | 6 +- dom/plugins/ipc/PluginModuleParent.cpp | 28 +- dom/power/WakeLock.cpp | 16 +- dom/presentation/PresentationAvailability.cpp | 3 +- dom/presentation/PresentationConnection.cpp | 44 +- .../PresentationConnectionList.cpp | 2 +- dom/presentation/PresentationRequest.cpp | 2 +- .../provider/MulticastDNSDeviceProvider.cpp | 15 +- dom/prio/test/gtest/TestPrioEncoder.cpp | 2 +- dom/promise/PromiseDebugging.cpp | 2 +- .../PrototypeDocumentContentSink.cpp | 21 +- dom/push/PushManager.cpp | 8 +- dom/push/PushNotifier.cpp | 20 +- dom/quota/ActorsParent.cpp | 158 +- dom/quota/InitializationTypes.h | 22 +- dom/quota/QuotaCommon.cpp | 8 +- dom/quota/QuotaCommon.h | 2 +- dom/quota/StorageManager.cpp | 12 +- dom/quota/test/gtest/TestQuotaManager.cpp | 22 +- dom/reporting/CrashReport.cpp | 8 +- dom/reporting/ReportDeliver.cpp | 5 +- dom/reporting/ReportingHeader.cpp | 6 +- .../tests/gtest/TestReportToParser.cpp | 102 +- dom/script/ScriptElement.cpp | 5 +- dom/script/ScriptLoader.cpp | 33 +- dom/security/CSPEvalChecker.cpp | 3 +- dom/security/DOMSecurityMonitor.cpp | 50 +- dom/security/FramingChecker.cpp | 15 +- dom/security/ReferrerInfo.cpp | 7 +- dom/security/SRICheck.cpp | 38 +- dom/security/SecFetch.cpp | 98 +- dom/security/featurepolicy/FeaturePolicy.cpp | 4 +- .../featurepolicy/FeaturePolicyParser.cpp | 16 +- .../featurepolicy/FeaturePolicyUtils.cpp | 5 +- .../test/gtest/TestFeaturePolicyParser.cpp | 105 +- dom/security/nsCSPContext.cpp | 22 +- dom/security/nsCSPParser.cpp | 23 +- dom/security/nsCSPService.cpp | 2 +- dom/security/nsCSPUtils.cpp | 6 +- dom/security/nsContentSecurityManager.cpp | 32 +- dom/security/nsContentSecurityUtils.cpp | 103 +- dom/security/nsHTTPSOnlyUtils.cpp | 2 +- dom/security/nsMixedContentBlocker.cpp | 5 +- .../test/gtest/TestFilenameEvalParser.cpp | 60 +- dom/serviceworkers/FetchEventOpChild.cpp | 5 +- dom/serviceworkers/ServiceWorker.cpp | 6 +- dom/serviceworkers/ServiceWorkerContainer.cpp | 16 +- dom/serviceworkers/ServiceWorkerEvents.cpp | 67 +- dom/serviceworkers/ServiceWorkerManager.cpp | 2 +- dom/serviceworkers/ServiceWorkerManager.h | 2 +- dom/serviceworkers/ServiceWorkerOp.cpp | 62 +- dom/serviceworkers/ServiceWorkerPrivate.cpp | 12 +- dom/serviceworkers/ServiceWorkerRegistrar.cpp | 9 +- .../ServiceWorkerRegistration.cpp | 6 +- .../ServiceWorkerRegistrationInfo.cpp | 3 +- .../ServiceWorkerScriptCache.cpp | 24 +- .../ServiceWorkerShutdownBlocker.cpp | 19 +- dom/serviceworkers/ServiceWorkerUpdateJob.cpp | 3 +- dom/serviceworkers/ServiceWorkerUtils.cpp | 14 +- .../test/gtest/TestReadWrite.cpp | 9 +- dom/smil/SMILCSSValueType.cpp | 3 +- dom/smil/SMILParserUtils.cpp | 8 +- dom/storage/LocalStorageCache.cpp | 2 +- dom/storage/Storage.cpp | 2 +- dom/storage/StorageDBThread.cpp | 51 +- dom/storage/StorageDBUpdater.cpp | 81 +- dom/storage/StorageObserver.cpp | 6 +- dom/svg/SVGContentUtils.cpp | 6 +- dom/svg/SVGFragmentIdentifier.cpp | 11 +- dom/svg/SVGScriptElement.cpp | 13 +- dom/system/linux/GpsdLocationProvider.cpp | 6 +- dom/system/nsDeviceSensors.cpp | 24 +- dom/url/URLSearchParams.cpp | 2 +- dom/url/URLWorker.cpp | 9 +- dom/vr/XRInputSource.cpp | 28 +- dom/vr/XRInputSourceArray.cpp | 6 +- dom/vr/XRPermissionRequest.cpp | 3 +- dom/vr/XRSession.cpp | 4 +- dom/vr/XRSystem.cpp | 9 +- dom/webauthn/U2FSoftTokenManager.cpp | 3 +- dom/webauthn/U2FTokenManager.cpp | 8 +- dom/webauthn/WebAuthnManager.cpp | 12 +- .../WebBrowserPersistLocalDocument.cpp | 20 +- dom/webbrowserpersist/nsWebBrowserPersist.cpp | 10 +- dom/websocket/WebSocket.cpp | 32 +- dom/workers/MessageEventRunnable.cpp | 6 +- dom/workers/RuntimeService.cpp | 54 +- dom/workers/ScriptLoader.cpp | 39 +- dom/workers/WorkerCSPEventListener.cpp | 4 +- dom/workers/WorkerDebugger.cpp | 6 +- dom/workers/WorkerError.cpp | 8 +- dom/workers/WorkerLoadInfo.cpp | 7 +- dom/workers/WorkerNavigator.cpp | 3 +- dom/workers/WorkerPrivate.cpp | 26 +- dom/workers/WorkerThread.cpp | 2 +- dom/workers/sharedworkers/SharedWorker.cpp | 4 +- .../sharedworkers/SharedWorkerChild.cpp | 6 +- dom/worklet/Worklet.cpp | 6 +- dom/worklet/WorkletThread.cpp | 2 +- dom/xhr/XMLHttpRequestMainThread.cpp | 42 +- dom/xhr/XMLHttpRequestWorker.cpp | 20 +- dom/xml/nsXMLPrettyPrinter.cpp | 5 +- dom/xslt/xpath/txCoreFunctionCall.cpp | 3 +- dom/xslt/xpath/txErrorExpr.cpp | 2 +- dom/xslt/xpath/txExprParser.cpp | 3 +- dom/xslt/xpath/txForwardContext.cpp | 2 +- dom/xslt/xpath/txFunctionCall.cpp | 5 +- dom/xslt/xpath/txNodeSetContext.cpp | 2 +- dom/xslt/xpath/txSingleNodeContext.h | 2 +- dom/xslt/xslt/txEXSLTFunctions.cpp | 6 +- dom/xslt/xslt/txExecutionState.cpp | 6 +- dom/xslt/xslt/txFormatNumberFunctionCall.cpp | 7 +- dom/xslt/xslt/txInstructions.cpp | 2 +- dom/xslt/xslt/txMozillaStylesheetCompiler.cpp | 2 +- dom/xslt/xslt/txMozillaTextOutput.cpp | 5 +- dom/xslt/xslt/txMozillaXMLOutput.cpp | 6 +- dom/xslt/xslt/txMozillaXSLTProcessor.cpp | 8 +- dom/xslt/xslt/txUnknownHandler.cpp | 6 +- .../xslt/txXSLTEnvironmentFunctionCall.cpp | 7 +- dom/xslt/xslt/txXSLTNumber.cpp | 4 +- dom/xul/ChromeObserver.cpp | 11 +- dom/xul/XULFrameElement.cpp | 2 +- dom/xul/XULTooltipElement.cpp | 5 +- dom/xul/nsXULContentSink.cpp | 9 +- dom/xul/nsXULElement.cpp | 8 +- dom/xul/nsXULElement.h | 5 +- dom/xul/nsXULPrototypeCache.cpp | 7 +- dom/xul/nsXULSortService.cpp | 2 +- editor/composer/nsEditingSession.cpp | 2 +- editor/libeditor/CSSEditUtils.cpp | 4 +- editor/libeditor/ChangeStyleTransaction.cpp | 2 +- editor/libeditor/EditorBase.cpp | 12 +- editor/libeditor/EditorEventListener.cpp | 78 +- editor/libeditor/HTMLAbsPositionEditor.cpp | 7 +- editor/libeditor/HTMLAnonymousNodeEditor.cpp | 27 +- editor/libeditor/HTMLEditUtils.cpp | 7 +- editor/libeditor/HTMLEditor.cpp | 38 +- editor/libeditor/HTMLEditorCommands.cpp | 6 +- editor/libeditor/HTMLEditorDataTransfer.cpp | 35 +- .../libeditor/HTMLEditorDocumentCommands.cpp | 8 +- editor/libeditor/HTMLEditorEventListener.cpp | 9 +- editor/libeditor/HTMLEditorObjectResizer.cpp | 61 +- editor/libeditor/HTMLInlineTableEditor.cpp | 31 +- editor/libeditor/HTMLStyleEditor.cpp | 8 +- editor/libeditor/TextEditSubActionHandler.cpp | 6 +- editor/libeditor/TextEditor.cpp | 26 +- editor/libeditor/TextEditor.h | 4 +- editor/libeditor/TextEditorDataTransfer.cpp | 2 +- editor/libeditor/WSRunObject.cpp | 9 +- editor/spellchecker/EditorSpellCheck.cpp | 2 +- editor/spellchecker/nsComposeTxtSrvFilter.cpp | 6 +- extensions/auth/nsAuthSSPI.cpp | 2 +- extensions/auth/nsAuthSambaNTLM.cpp | 8 +- extensions/permissions/PermissionManager.cpp | 252 ++- .../test/gtest/PermissionManagerTest.cpp | 9 +- .../pref/autoconfig/src/nsAutoConfig.cpp | 10 +- .../autoconfig/src/nsJSConfigTriggers.cpp | 6 +- .../pref/autoconfig/src/nsReadConfig.cpp | 9 +- .../spellcheck/hunspell/glue/mozHunspell.cpp | 2 +- .../spellcheck/src/mozInlineSpellChecker.cpp | 12 +- gfx/config/gfxConfigManager.cpp | 70 +- gfx/config/gfxFeature.cpp | 5 +- gfx/gl/GLContext.cpp | 34 +- gfx/gl/GLContextProviderCGL.mm | 4 +- gfx/gl/GLContextProviderEGL.cpp | 15 +- gfx/gl/GLContextProviderNull.cpp | 2 +- gfx/gl/GLLibraryEGL.cpp | 29 +- gfx/ipc/GPUProcessManager.cpp | 27 +- gfx/layers/MemoryPressureObserver.cpp | 6 +- gfx/layers/PaintThread.cpp | 3 +- gfx/layers/ProfilerScreenshots.cpp | 4 +- gfx/layers/apz/src/AsyncPanZoomController.cpp | 4 +- gfx/layers/apz/src/InputBlockState.cpp | 3 +- gfx/layers/apz/util/APZEventState.cpp | 2 +- gfx/layers/composite/FPSCounter.cpp | 4 +- gfx/layers/d3d11/CompositorD3D11.cpp | 5 +- gfx/layers/d3d11/MLGDeviceD3D11.cpp | 2 +- gfx/layers/ipc/CanvasThread.cpp | 2 +- gfx/layers/opengl/CompositorOGL.cpp | 14 +- gfx/thebes/DeviceManagerDx.cpp | 40 +- gfx/thebes/SharedFontList.cpp | 7 +- gfx/thebes/gfxDWriteFontList.cpp | 8 +- gfx/thebes/gfxDWriteFonts.cpp | 2 +- gfx/thebes/gfxFT2FontList.cpp | 11 +- gfx/thebes/gfxFcPlatformFontList.cpp | 12 +- gfx/thebes/gfxGDIFontList.cpp | 2 +- gfx/thebes/gfxMacPlatformFontList.mm | 4 +- gfx/thebes/gfxPlatform.cpp | 53 +- gfx/thebes/gfxPlatformFontList.cpp | 14 +- gfx/thebes/gfxPlatformGtk.cpp | 2 +- gfx/thebes/gfxPlatformMac.cpp | 2 +- gfx/thebes/gfxSVGGlyphs.cpp | 6 +- gfx/thebes/gfxUserFontSet.cpp | 4 +- gfx/thebes/gfxUtils.cpp | 3 +- gfx/thebes/gfxWindowsPlatform.cpp | 44 +- gfx/vr/VRManager.cpp | 2 +- gfx/vr/ipc/VRProcessManager.cpp | 4 +- gfx/vr/nsFxrCommandLineHandler.cpp | 3 +- gfx/vr/service/OculusSession.cpp | 2 +- gfx/vr/service/OpenVRSession.cpp | 2 +- hal/HalWakeLock.cpp | 3 +- image/DecodePool.cpp | 2 +- image/RasterImage.cpp | 4 +- image/SVGDocumentWrapper.cpp | 5 +- image/VectorImage.cpp | 16 +- image/build/nsImageModule.cpp | 13 +- image/decoders/icon/android/nsIconChannel.cpp | 2 +- image/decoders/icon/gtk/nsIconChannel.cpp | 6 +- image/decoders/icon/nsIconURI.cpp | 2 +- image/decoders/icon/win/nsIconChannel.cpp | 2 +- image/encoders/jpeg/nsJPEGEncoder.cpp | 2 +- image/imgLoader.cpp | 6 +- image/imgTools.cpp | 3 +- .../hyphenation/glue/nsHyphenationManager.cpp | 14 +- intl/l10n/FluentResource.cpp | 4 +- intl/locale/LocaleService.cpp | 2 +- intl/locale/OSPreferences.cpp | 2 +- intl/locale/nsLanguageAtomService.cpp | 2 +- intl/locale/tests/gtest/TestCollation.cpp | 8 +- intl/locale/tests/gtest/TestLocaleService.cpp | 8 +- .../gtest/TestLocaleServiceNegotiate.cpp | 10 +- intl/locale/windows/OSPreferences_win.cpp | 8 +- intl/strres/nsStringBundle.cpp | 2 +- intl/uconv/nsTextToSubURI.cpp | 3 +- ipc/glue/CrashReporterHost.cpp | 3 +- ipc/glue/ForkServer.cpp | 3 +- ipc/glue/GeckoChildProcessHost.cpp | 11 +- ipc/glue/IPCMessageUtils.h | 6 +- ipc/glue/IdleSchedulerParent.cpp | 4 +- ipc/glue/LibrarySandboxPreload.cpp | 4 +- ipc/glue/ProtocolUtils.cpp | 2 +- ipc/glue/ScopedXREEmbed.cpp | 2 +- ipc/glue/WindowsMessageLoop.cpp | 4 +- ipc/mscom/COMPtrHolder.h | 3 +- ipc/mscom/ProxyStream.cpp | 19 +- ipc/mscom/Utils.cpp | 4 +- js/xpconnect/loader/ScriptPreloader.cpp | 16 +- js/xpconnect/loader/ScriptPreloader.h | 3 +- js/xpconnect/loader/URLPreloader.cpp | 19 +- js/xpconnect/loader/mozJSComponentLoader.cpp | 12 +- js/xpconnect/loader/mozJSSubScriptLoader.cpp | 8 +- js/xpconnect/src/Sandbox.cpp | 4 +- js/xpconnect/src/XPCConvert.cpp | 3 +- js/xpconnect/src/XPCJSRuntime.cpp | 546 +++--- js/xpconnect/src/XPCShellImpl.cpp | 16 +- js/xpconnect/src/nsXPConnect.cpp | 10 +- js/xpconnect/src/xpcprivate.h | 4 +- js/xpconnect/wrappers/AccessCheck.cpp | 8 +- layout/base/AccessibleCaret.cpp | 20 +- layout/base/AccessibleCaretManager.cpp | 13 +- layout/base/GeckoMVMContext.cpp | 2 +- layout/base/LayoutTelemetryTools.cpp | 24 +- layout/base/MobileViewportManager.cpp | 8 +- layout/base/PresShell.cpp | 11 +- layout/base/ZoomConstraintsClient.cpp | 10 +- layout/base/nsCSSFrameConstructor.cpp | 6 +- layout/base/nsDocumentViewer.cpp | 22 +- layout/base/nsPresContext.cpp | 9 +- layout/base/nsRefreshDriver.cpp | 12 +- layout/build/nsContentDLF.cpp | 6 +- layout/forms/nsColorControlFrame.cpp | 4 +- layout/forms/nsComboboxControlFrame.cpp | 23 +- layout/forms/nsDateTimeControlFrame.h | 2 +- layout/forms/nsFieldSetFrame.h | 2 +- layout/forms/nsFileControlFrame.cpp | 18 +- layout/forms/nsGfxButtonControlFrame.cpp | 2 +- layout/forms/nsHTMLButtonControlFrame.h | 2 +- layout/forms/nsImageControlFrame.cpp | 2 +- layout/forms/nsLegendFrame.cpp | 2 +- layout/forms/nsListControlFrame.cpp | 50 +- layout/forms/nsMeterFrame.h | 2 +- layout/forms/nsNumberControlFrame.cpp | 2 +- layout/forms/nsNumberControlFrame.h | 2 +- layout/forms/nsProgressFrame.h | 2 +- layout/forms/nsRangeFrame.cpp | 6 +- layout/forms/nsRangeFrame.h | 2 +- layout/generic/BlockReflowInput.cpp | 6 +- layout/generic/ColumnSetWrapperFrame.cpp | 2 +- layout/generic/DetailsFrame.h | 2 +- layout/generic/ScrollAnchorContainer.cpp | 2 +- layout/generic/ScrollbarActivity.cpp | 30 +- layout/generic/ViewportFrame.cpp | 2 +- layout/generic/nsBackdropFrame.cpp | 2 +- layout/generic/nsBlockFrame.cpp | 2 +- layout/generic/nsBulletFrame.cpp | 2 +- layout/generic/nsCanvasFrame.cpp | 19 +- layout/generic/nsColumnSetFrame.h | 2 +- layout/generic/nsFirstLetterFrame.cpp | 2 +- layout/generic/nsFlexContainerFrame.cpp | 2 +- layout/generic/nsFrame.cpp | 2 +- layout/generic/nsFrameSetFrame.cpp | 6 +- layout/generic/nsGfxScrollFrame.cpp | 41 +- layout/generic/nsGridContainerFrame.cpp | 6 +- layout/generic/nsHTMLCanvasFrame.cpp | 2 +- layout/generic/nsImageFrame.cpp | 2 +- layout/generic/nsImageMap.cpp | 14 +- layout/generic/nsInlineFrame.cpp | 4 +- layout/generic/nsPageContentFrame.cpp | 2 +- layout/generic/nsPageFrame.cpp | 4 +- layout/generic/nsPageSequenceFrame.cpp | 2 +- layout/generic/nsPlaceholderFrame.cpp | 2 +- layout/generic/nsPluginFrame.cpp | 5 +- layout/generic/nsRubyBaseContainerFrame.cpp | 2 +- layout/generic/nsRubyBaseFrame.cpp | 2 +- layout/generic/nsRubyFrame.cpp | 2 +- layout/generic/nsRubyTextContainerFrame.cpp | 2 +- layout/generic/nsRubyTextFrame.cpp | 2 +- layout/generic/nsSubDocumentFrame.cpp | 2 +- layout/generic/nsTextFrame.cpp | 21 +- layout/generic/nsVideoFrame.cpp | 8 +- layout/mathml/nsMathMLChar.cpp | 10 +- layout/mathml/nsMathMLContainerFrame.cpp | 5 +- layout/mathml/nsMathMLOperators.cpp | 2 +- layout/mathml/nsMathMLmactionFrame.cpp | 18 +- layout/mathml/nsMathMLmtableFrame.cpp | 5 +- layout/painting/nsCSSRenderingBorders.cpp | 2 +- layout/painting/nsDisplayList.cpp | 18 +- .../PrintPreviewUserEventSuppressor.cpp | 57 +- layout/printing/nsPrintJob.cpp | 10 +- layout/style/FontFaceSet.cpp | 15 +- layout/style/FontPreloader.cpp | 11 +- layout/style/GeckoBindings.cpp | 4 +- layout/style/GlobalStyleSheetCache.cpp | 29 +- layout/style/ImageLoader.cpp | 3 +- layout/style/Loader.cpp | 40 +- layout/style/MediaQueryList.cpp | 2 +- layout/style/StyleSheet.cpp | 2 +- layout/style/nsCSSAnonBoxes.cpp | 3 +- layout/style/nsCSSProps.cpp | 2 +- layout/style/nsCSSPseudoElements.cpp | 6 +- layout/style/nsComputedDOMStyle.cpp | 16 +- layout/style/test/gtest/ImportScannerTest.cpp | 18 +- layout/style/test/gtest/StyloParsingBench.cpp | 4 +- layout/svg/SVGAFrame.cpp | 2 +- layout/svg/SVGContextPaint.cpp | 4 +- layout/svg/SVGFEContainerFrame.cpp | 2 +- layout/svg/SVGFEImageFrame.cpp | 2 +- layout/svg/SVGFELeafFrame.cpp | 2 +- layout/svg/SVGFEUnstyledLeafFrame.cpp | 2 +- layout/svg/SVGForeignObjectFrame.h | 2 +- layout/svg/SVGGFrame.h | 2 +- layout/svg/SVGGenericContainerFrame.h | 2 +- layout/svg/SVGGeometryFrame.h | 2 +- layout/svg/SVGImageFrame.h | 2 +- layout/svg/SVGInnerSVGFrame.h | 2 +- layout/svg/SVGMarkerFrame.h | 4 +- layout/svg/SVGMaskFrame.h | 2 +- layout/svg/SVGObserverUtils.cpp | 3 +- layout/svg/SVGSymbolFrame.h | 2 +- layout/svg/SVGTextFrame.h | 2 +- layout/svg/SVGUseFrame.h | 2 +- layout/svg/SVGViewFrame.cpp | 2 +- layout/svg/nsSVGClipPathFrame.h | 2 +- layout/svg/nsSVGGradientFrame.h | 6 +- layout/svg/nsSVGOuterSVGFrame.h | 4 +- layout/svg/nsSVGPatternFrame.h | 2 +- layout/svg/nsSVGStopFrame.cpp | 2 +- layout/svg/nsSVGSwitchFrame.cpp | 2 +- layout/tables/nsTableCellFrame.cpp | 4 +- layout/tables/nsTableColFrame.cpp | 2 +- layout/tables/nsTableColGroupFrame.cpp | 2 +- layout/tables/nsTableFrame.cpp | 7 +- layout/tables/nsTableRowFrame.cpp | 2 +- layout/tables/nsTableRowGroupFrame.cpp | 2 +- layout/tables/nsTableWrapperFrame.cpp | 2 +- .../layout-debug/src/nsLayoutDebugCLH.cpp | 23 +- .../src/nsLayoutDebuggingTools.cpp | 12 +- layout/xul/grid/nsGridRowGroupFrame.h | 2 +- layout/xul/grid/nsGridRowLeafFrame.h | 2 +- layout/xul/nsBoxFrame.cpp | 2 +- layout/xul/nsButtonBoxFrame.cpp | 6 +- layout/xul/nsButtonBoxFrame.h | 2 +- layout/xul/nsDeckFrame.h | 2 +- layout/xul/nsDocElementBoxFrame.cpp | 6 +- layout/xul/nsImageBoxFrame.cpp | 2 +- layout/xul/nsLeafBoxFrame.cpp | 2 +- layout/xul/nsMenuBarFrame.h | 2 +- layout/xul/nsMenuBarListener.cpp | 53 +- layout/xul/nsMenuFrame.cpp | 10 +- layout/xul/nsMenuFrame.h | 2 +- layout/xul/nsMenuPopupFrame.cpp | 7 +- layout/xul/nsMenuPopupFrame.h | 2 +- layout/xul/nsPopupSetFrame.h | 2 +- layout/xul/nsResizerFrame.cpp | 13 +- layout/xul/nsRootBoxFrame.cpp | 2 +- layout/xul/nsScrollbarButtonFrame.cpp | 2 +- layout/xul/nsScrollbarButtonFrame.h | 5 +- layout/xul/nsScrollbarFrame.cpp | 18 +- layout/xul/nsScrollbarFrame.h | 2 +- layout/xul/nsSliderFrame.cpp | 26 +- layout/xul/nsSliderFrame.h | 4 +- layout/xul/nsSplitterFrame.cpp | 52 +- layout/xul/nsSplitterFrame.h | 2 +- layout/xul/nsStackFrame.h | 2 +- layout/xul/nsTextBoxFrame.cpp | 6 +- layout/xul/nsXULLabelFrame.cpp | 2 +- layout/xul/nsXULPopupManager.cpp | 34 +- layout/xul/nsXULTooltipListener.cpp | 55 +- layout/xul/tree/nsTreeBodyFrame.cpp | 30 +- layout/xul/tree/nsTreeContentView.cpp | 8 +- layout/xul/tree/nsTreeSelection.cpp | 7 +- layout/xul/tree/nsTreeUtils.cpp | 3 +- media/mtransport/ipc/WebrtcTCPSocket.cpp | 5 +- media/mtransport/nr_socket_prsock.cpp | 2 +- .../test/proxy_tunnel_socket_unittest.cpp | 2 +- .../test/webrtcproxychannel_unittest.cpp | 2 +- .../src/media-conduit/WebrtcGmpVideoCodec.cpp | 18 +- .../src/mediapipeline/MediaPipeline.cpp | 2 +- .../peerconnection/MediaTransportHandler.cpp | 2 +- .../src/peerconnection/PeerConnectionCtx.cpp | 6 +- .../src/peerconnection/PeerConnectionImpl.cpp | 13 +- .../peerconnection/PeerConnectionMedia.cpp | 2 +- .../src/peerconnection/RTCDTMFSender.cpp | 4 +- .../src/peerconnection/RTCRtpReceiver.cpp | 15 +- .../src/peerconnection/RemoteTrackSource.h | 3 +- .../WebrtcGlobalInformation.cpp | 3 +- .../src/sdp/ParsingResultComparer.cpp | 43 +- .../geckoview/GeckoViewExternalAppService.cpp | 8 +- .../components/geckoview/GeckoViewHistory.cpp | 8 +- modules/libjar/nsJARInputStream.cpp | 3 +- modules/libjar/nsJARURI.cpp | 6 +- modules/libjar/zipwriter/nsZipHeader.cpp | 6 +- modules/libjar/zipwriter/nsZipWriter.cpp | 2 +- modules/libpref/Preferences.cpp | 21 +- .../test/gtest/CallbackAndVarCacheOrder.cpp | 39 +- mozglue/tests/gtest/TestNativeNtGTest.cpp | 8 +- netwerk/base/DefaultURI.cpp | 5 +- netwerk/base/Predictor.cpp | 12 +- netwerk/base/ProxyAutoConfig.cpp | 21 +- netwerk/base/mozurl/MozURL.h | 4 +- .../base/nsINetworkInterceptController.idl | 8 +- netwerk/base/nsIOService.cpp | 19 +- netwerk/base/nsIncrementalDownload.cpp | 34 +- netwerk/base/nsMediaFragmentURIParser.cpp | 4 +- netwerk/base/nsNetUtil.cpp | 17 +- netwerk/base/nsProtocolProxyService.cpp | 2 +- netwerk/base/nsSimpleURI.cpp | 19 +- netwerk/base/nsSocketTransport2.cpp | 2 +- netwerk/base/nsSocketTransportService2.cpp | 3 +- netwerk/base/nsStandardURL.cpp | 13 +- netwerk/base/nsStreamTransportService.cpp | 2 +- netwerk/cache/nsCacheService.cpp | 6 +- netwerk/cache/nsDiskCacheDeviceSQL.cpp | 137 +- netwerk/cache2/AppCacheStorage.cpp | 2 +- netwerk/cache2/CacheFileContextEvictor.cpp | 6 +- netwerk/cache2/CacheFileIOManager.cpp | 14 +- netwerk/cache2/CacheFileUtils.cpp | 3 +- netwerk/cache2/CacheIndex.cpp | 42 +- netwerk/cache2/CacheStorageService.cpp | 2 +- netwerk/cache2/OldWrappers.cpp | 12 +- netwerk/cookie/CookieCommons.cpp | 7 +- netwerk/cookie/CookieJarSettings.cpp | 18 +- netwerk/cookie/CookiePersistentStorage.cpp | 559 +++--- netwerk/cookie/CookieService.cpp | 18 +- netwerk/dns/GetAddrInfo.cpp | 2 +- netwerk/dns/TRR.cpp | 37 +- netwerk/dns/TRRService.cpp | 2 +- netwerk/dns/nsDNSService2.cpp | 2 +- netwerk/dns/nsHostResolver.cpp | 2 +- netwerk/dns/nsIDNService.cpp | 10 +- netwerk/ipc/DocumentLoadListener.cpp | 8 +- netwerk/protocol/about/nsAboutBlank.cpp | 6 +- netwerk/protocol/about/nsAboutCache.cpp | 19 +- netwerk/protocol/about/nsAboutCacheEntry.cpp | 16 +- .../protocol/about/nsAboutProtocolHandler.cpp | 9 +- netwerk/protocol/about/nsAboutProtocolUtils.h | 2 +- netwerk/protocol/file/nsFileChannel.cpp | 2 +- .../protocol/file/nsFileProtocolHandler.cpp | 3 +- .../protocol/ftp/nsFtpConnectionThread.cpp | 25 +- netwerk/protocol/gio/nsGIOProtocolHandler.cpp | 9 +- netwerk/protocol/http/ASpdySession.cpp | 2 +- netwerk/protocol/http/AlternateServices.cpp | 12 +- netwerk/protocol/http/Http2Compression.cpp | 142 +- netwerk/protocol/http/Http3Session.cpp | 10 +- netwerk/protocol/http/HttpBaseChannel.cpp | 39 +- netwerk/protocol/http/HttpChannelChild.cpp | 10 +- netwerk/protocol/http/HttpTrafficAnalyzer.cpp | 6 +- netwerk/protocol/http/InterceptedChannel.cpp | 7 +- .../protocol/http/InterceptedHttpChannel.cpp | 7 +- netwerk/protocol/http/NullHttpChannel.cpp | 2 +- netwerk/protocol/http/nsCORSListenerProxy.cpp | 45 +- netwerk/protocol/http/nsHttp.cpp | 4 +- .../http/nsHttpActivityDistributor.cpp | 5 +- netwerk/protocol/http/nsHttpChannel.cpp | 132 +- .../http/nsHttpChannelAuthProvider.cpp | 10 +- netwerk/protocol/http/nsHttpConnection.cpp | 15 +- .../protocol/http/nsHttpConnectionInfo.cpp | 4 +- netwerk/protocol/http/nsHttpConnectionMgr.cpp | 10 +- netwerk/protocol/http/nsHttpHandler.cpp | 18 +- netwerk/protocol/http/nsHttpRequestHead.cpp | 2 +- netwerk/protocol/http/nsHttpResponseHead.cpp | 5 +- netwerk/protocol/http/nsHttpTransaction.cpp | 25 +- .../protocol/res/ExtensionProtocolHandler.cpp | 5 +- .../protocol/res/PageThumbProtocolHandler.cpp | 4 +- .../res/SubstitutingProtocolHandler.cpp | 3 +- netwerk/protocol/res/nsResProtocolHandler.cpp | 5 +- .../viewsource/nsViewSourceChannel.cpp | 20 +- .../protocol/websocket/WebSocketChannel.cpp | 50 +- .../websocket/WebSocketChannelParent.cpp | 2 +- netwerk/sctp/datachannel/DataChannel.cpp | 2 +- netwerk/socket/nsNamedPipeIOLayer.cpp | 2 +- netwerk/socket/nsSOCKSIOLayer.cpp | 2 +- netwerk/socket/nsSOCKSSocketProvider.cpp | 2 +- .../converters/mozTXTToHTMLConv.cpp | 2 +- .../streamconv/converters/nsIndexedToHTML.cpp | 15 +- .../converters/nsMultiMixedConv.cpp | 12 +- .../converters/nsUnknownDecoder.cpp | 10 +- netwerk/system/netlink/NetlinkService.cpp | 2 +- netwerk/system/win32/nsNotifyAddrListener.cpp | 33 +- netwerk/test/fuzz/TestHttpFuzzing.cpp | 2 +- netwerk/test/fuzz/TestWebsocketFuzzing.cpp | 5 +- netwerk/test/gtest/TestBind.cpp | 3 +- netwerk/test/gtest/TestCookie.cpp | 88 +- netwerk/test/gtest/TestHeaders.cpp | 11 +- netwerk/test/gtest/TestHttpResponseHead.cpp | 23 +- .../test/gtest/TestInputStreamTransport.cpp | 5 +- netwerk/test/gtest/TestMozURL.cpp | 61 +- .../test/gtest/TestSocketTransportService.cpp | 125 +- netwerk/test/gtest/TestStandardURL.cpp | 85 +- netwerk/test/gtest/TestUDPSocket.cpp | 2 +- netwerk/test/gtest/TestURIMutator.cpp | 55 +- .../url-classifier/UrlClassifierCommon.cpp | 16 +- ...lassifierFeatureCryptominingAnnotation.cpp | 19 +- ...lassifierFeatureCryptominingProtection.cpp | 16 +- .../UrlClassifierFeatureFactory.cpp | 8 +- ...ssifierFeatureFingerprintingAnnotation.cpp | 20 +- ...ssifierFeatureFingerprintingProtection.cpp | 18 +- .../UrlClassifierFeatureLoginReputation.cpp | 17 +- ...ssifierFeatureSocialTrackingAnnotation.cpp | 24 +- ...ssifierFeatureSocialTrackingProtection.cpp | 18 +- ...UrlClassifierFeatureTrackingAnnotation.cpp | 33 +- ...UrlClassifierFeatureTrackingProtection.cpp | 16 +- .../url-classifier/nsChannelClassifier.cpp | 3 +- parser/html/nsHtml5StreamParser.cpp | 2 +- parser/html/nsHtml5TreeOpExecutor.cpp | 13 +- parser/html/nsHtml5TreeOperation.cpp | 6 +- parser/html/nsParserUtils.cpp | 2 +- parser/htmlparser/nsExpatDriver.cpp | 6 +- parser/htmlparser/nsHTMLTags.cpp | 4 +- parser/htmlparser/nsParser.cpp | 4 +- security/apps/AppSignatureVerification.cpp | 15 +- security/manager/pki/nsNSSDialogs.cpp | 22 +- security/manager/ssl/CertBlocklist.cpp | 10 +- .../manager/ssl/ContentSignatureVerifier.cpp | 4 +- security/manager/ssl/DataStorage.cpp | 2 +- security/manager/ssl/OSReauthenticator.cpp | 35 +- .../manager/ssl/SSLServerCertVerification.cpp | 10 +- security/manager/ssl/SharedSSLState.cpp | 3 +- .../manager/ssl/nsCertOverrideService.cpp | 6 +- security/manager/ssl/nsCertTree.cpp | 20 +- security/manager/ssl/nsNSSCallbacks.cpp | 46 +- security/manager/ssl/nsNSSComponent.cpp | 6 +- security/manager/ssl/nsNSSIOLayer.cpp | 6 +- .../ssl/tests/gtest/DataStorageTest.cpp | 25 +- .../ssl/tests/gtest/TLSIntoleranceTest.cpp | 3 +- .../broker/SandboxBrokerPolicyFactory.cpp | 16 +- .../win/src/sandboxbroker/sandboxBroker.cpp | 45 +- .../component/IdentityCryptoService.cpp | 4 +- startupcache/StartupCache.cpp | 4 +- startupcache/test/TestStartupCache.cpp | 4 +- storage/TelemetryVFS.cpp | 2 +- storage/VacuumManager.cpp | 3 +- storage/mozStorageAsyncStatement.cpp | 8 +- storage/mozStorageConnection.cpp | 45 +- storage/mozStorageHelper.h | 8 +- storage/mozStorageService.cpp | 18 +- storage/mozStorageStatement.cpp | 8 +- storage/test/gtest/storage_test_harness.h | 5 +- storage/test/gtest/test_AsXXX_helpers.cpp | 6 +- ...st_asyncStatementExecution_transaction.cpp | 92 +- ..._async_callbacks_with_spun_event_loops.cpp | 19 +- storage/test/gtest/test_binding_params.cpp | 41 +- .../gtest/test_spinningSynchronousClose.cpp | 6 +- storage/test/gtest/test_statement_scoper.cpp | 10 +- .../test/gtest/test_transaction_helper.cpp | 28 +- storage/test/gtest/test_true_async.cpp | 36 +- storage/test/gtest/test_unlock_notify.cpp | 23 +- toolkit/components/alerts/nsXULAlerts.cpp | 2 +- .../components/antitracking/AntiTrackingLog.h | 8 +- .../antitracking/AntiTrackingUtils.cpp | 8 +- .../antitracking/ContentBlocking.cpp | 2 +- .../antitracking/ContentBlockingAllowList.cpp | 7 +- .../antitracking/ContentBlockingNotifier.cpp | 10 +- .../antitracking/ContentBlockingNotifier.h | 2 +- .../ContentBlockingUserInteraction.h | 2 +- .../DynamicFpiRedirectHeuristic.cpp | 8 +- .../antitracking/RejectForeignAllowList.cpp | 5 +- .../autocomplete/nsAutoCompleteController.cpp | 2 +- .../BackgroundHangMonitor.cpp | 2 +- .../backgroundhangmonitor/HangAnnotations.cpp | 4 +- .../backgroundhangmonitor/HangDetails.cpp | 3 +- .../clearsitedata/ClearSiteData.cpp | 6 +- .../extensions/ExtensionPolicyService.cpp | 11 +- .../extensions/webrequest/ChannelWrapper.cpp | 11 +- .../extensions/webrequest/StreamFilter.cpp | 6 +- .../webrequest/StreamFilterChild.cpp | 8 +- .../webrequest/StreamFilterParent.cpp | 7 +- .../filewatcher/NativeFileWatcherWin.cpp | 3 +- .../osfile/NativeOSFileInternals.cpp | 58 +- .../nsParentalControlsServiceWin.cpp | 2 +- toolkit/components/places/Database.cpp | 561 +++--- toolkit/components/places/FaviconHelpers.cpp | 72 +- toolkit/components/places/Helpers.cpp | 2 +- toolkit/components/places/History.cpp | 67 +- .../places/PageIconProtocolHandler.cpp | 7 +- toolkit/components/places/SQLFunctions.cpp | 85 +- toolkit/components/places/Shutdown.cpp | 8 +- .../places/nsAnnoProtocolHandler.cpp | 10 +- .../components/places/nsAnnotationService.cpp | 55 +- .../components/places/nsFaviconService.cpp | 32 +- toolkit/components/places/nsNavBookmarks.cpp | 180 +- toolkit/components/places/nsNavHistory.cpp | 244 ++- toolkit/components/places/nsNavHistory.h | 4 +- .../components/places/nsNavHistoryQuery.cpp | 40 +- .../components/places/nsNavHistoryResult.cpp | 15 +- toolkit/components/places/nsPlacesIndexes.h | 6 +- toolkit/components/places/nsPlacesTables.h | 36 +- toolkit/components/places/nsPlacesTriggers.h | 36 +- .../places/tests/gtest/places_test_harness.h | 9 +- .../places/tests/gtest/test_IHistory.cpp | 5 +- .../components/printingui/nsPrintProgress.cpp | 8 +- .../prompts/docs/nsIPromptService.rst | 16 +- .../ApplicationReputation.cpp | 61 +- .../resistfingerprinting/nsRFPService.cpp | 4 +- .../satchel/nsFormFillController.cpp | 4 +- .../sessionstore/SessionStoreListener.cpp | 33 +- .../sessionstore/SessionStoreUtils.cpp | 29 +- toolkit/components/startup/nsAppStartup.cpp | 13 +- .../components/telemetry/core/Telemetry.cpp | 13 +- .../telemetry/core/TelemetryEvent.cpp | 36 +- .../telemetry/core/TelemetryHistogram.cpp | 53 +- .../telemetry/core/TelemetryScalar.cpp | 4 +- .../telemetry/docs/collection/origin.rst | 4 +- .../telemetry/docs/collection/scalars.rst | 2 +- .../other/TelemetryIOInterposeObserver.cpp | 2 +- .../telemetry/other/UntrustedModules.cpp | 4 +- .../tests/gtest/TelemetryTestHelpers.cpp | 21 +- .../telemetry/tests/gtest/TestCounters.cpp | 16 +- .../telemetry/tests/gtest/TestHistograms.cpp | 101 +- .../telemetry/tests/gtest/TestOrigins.cpp | 10 +- .../telemetry/tests/gtest/TestScalars.cpp | 60 +- .../components/terminator/nsTerminator.cpp | 2 +- .../typeaheadfind/nsTypeAheadFind.cpp | 6 +- .../components/url-classifier/Classifier.cpp | 53 +- .../components/url-classifier/HashStore.cpp | 8 +- .../components/url-classifier/LookupCache.cpp | 34 +- .../url-classifier/LookupCacheV4.cpp | 10 +- .../url-classifier/ProtocolParser.cpp | 29 +- .../VariableLengthPrefixSet.cpp | 4 +- .../nsUrlClassifierDBService.cpp | 44 +- .../nsUrlClassifierStreamUpdater.cpp | 26 +- .../url-classifier/nsUrlClassifierUtils.cpp | 20 +- .../url-classifier/tests/gtest/Common.cpp | 2 +- .../url-classifier/tests/gtest/Common.h | 4 +- .../tests/gtest/TestCaching.cpp | 45 +- .../tests/gtest/TestChunkSet.cpp | 2 +- .../tests/gtest/TestClassifier.cpp | 6 +- .../tests/gtest/TestFailUpdate.cpp | 6 +- .../tests/gtest/TestLookupCacheV4.cpp | 18 +- .../tests/gtest/TestURLsAndHashing.cpp | 35 +- .../gtest/TestUrlClassifierTableUpdateV4.cpp | 8 +- .../gtest/TestVariableLengthPrefixSet.cpp | 34 +- toolkit/components/viaduct/ViaductRequest.cpp | 18 +- .../windowwatcher/nsAutoWindowStateHelper.cpp | 3 +- .../windowwatcher/nsWindowWatcher.cpp | 8 +- .../xulstore/tests/gtest/TestXULStore.cpp | 56 +- toolkit/crashreporter/InjectCrashReporter.cpp | 2 +- toolkit/crashreporter/nsExceptionHandler.cpp | 71 +- toolkit/library/gtest/TestUCRTDepends.cpp | 2 +- .../mozapps/extensions/AddonContentPolicy.cpp | 5 +- .../extensions/AddonManagerStartup.cpp | 2 +- toolkit/profile/nsToolkitProfileService.cpp | 37 +- toolkit/system/gnome/nsAlertsIconListener.cpp | 2 +- .../osxproxy/nsOSXSystemProxySettings.mm | 4 +- .../tests/gtest/TestProxyBypassRules.cpp | 67 +- .../unixproxy/nsUnixSystemProxySettings.cpp | 22 +- .../tests/gtest/TestProxyBypassRules.cpp | 67 +- toolkit/xre/ModuleEvaluator.cpp | 2 +- toolkit/xre/UntrustedModulesProcessor.cpp | 3 +- toolkit/xre/nsAppRunner.cpp | 44 +- toolkit/xre/nsAppStartupNotifier.cpp | 2 +- toolkit/xre/nsConsoleWriter.cpp | 2 +- toolkit/xre/nsNativeAppSupportUnix.cpp | 5 +- toolkit/xre/nsUpdateDriver.cpp | 24 +- toolkit/xre/nsXREDirProvider.cpp | 39 +- .../test/gtest/TestCompatVersionCompare.cpp | 3 +- .../interface/harness/FuzzerTestHarness.h | 4 +- tools/profiler/core/ProfilerBacktrace.cpp | 2 +- tools/profiler/core/platform.cpp | 2 +- tools/profiler/core/shared-libraries-win32.cc | 12 +- tools/profiler/gecko/nsProfiler.cpp | 2 +- tools/profiler/tests/gtest/GeckoProfiler.cpp | 53 +- uriloader/base/nsURILoader.cpp | 4 +- .../exthandler/ExternalHelperAppParent.cpp | 3 +- .../android/nsOSHelperAppService.cpp | 4 +- .../exthandler/mac/nsOSHelperAppService.mm | 2 +- .../exthandler/nsExternalHelperAppService.cpp | 10 +- uriloader/exthandler/nsMIMEInfoImpl.cpp | 2 +- .../exthandler/unix/nsOSHelperAppService.cpp | 34 +- uriloader/exthandler/win/nsMIMEInfoWin.cpp | 41 +- .../exthandler/win/nsOSHelperAppService.cpp | 12 +- uriloader/prefetch/nsOfflineCacheUpdate.cpp | 14 +- .../prefetch/nsOfflineCacheUpdateService.cpp | 8 +- uriloader/prefetch/nsPrefetchService.cpp | 10 +- uriloader/preload/FetchPreloader.cpp | 2 +- uriloader/preload/PreloadService.cpp | 3 +- uriloader/preload/PreloaderBase.cpp | 8 +- .../preload/gtest/TestFetchPreloader.cpp | 126 +- widget/GfxInfoBase.cpp | 11 +- widget/TextEventDispatcher.cpp | 15 +- widget/WidgetEventImpl.cpp | 6 +- widget/android/AndroidAlerts.cpp | 2 +- widget/android/EventDispatcher.cpp | 6 +- widget/android/jni/Utils.cpp | 3 +- widget/android/nsAppShell.cpp | 7 +- .../android/nsPrintSettingsServiceAndroid.cpp | 2 +- widget/android/nsWindow.cpp | 2 +- widget/cocoa/TextInputHandler.mm | 3 +- widget/cocoa/nsChildView.mm | 8 +- widget/cocoa/nsDeviceContextSpecX.mm | 9 +- widget/cocoa/nsFilePicker.mm | 4 +- widget/cocoa/nsMacCursor.mm | 4 +- widget/cocoa/nsMenuBarX.mm | 70 +- widget/cocoa/nsMenuItemX.mm | 10 +- widget/cocoa/nsMenuUtilsX.mm | 2 +- widget/cocoa/nsMenuX.mm | 8 +- widget/cocoa/nsNativeThemeCocoa.mm | 13 +- widget/gtk/WakeLockListener.cpp | 5 +- widget/gtk/nsClipboard.cpp | 6 +- widget/gtk/nsDragService.cpp | 4 +- widget/gtk/nsGtkKeyUtils.cpp | 92 +- widget/gtk/nsLookAndFeel.cpp | 2 +- widget/gtk/nsPSPrinters.cpp | 6 +- widget/gtk/nsPrintSettingsGTK.cpp | 2 +- widget/gtk/nsWindow.cpp | 6 +- widget/nsBaseFilePicker.cpp | 2 +- widget/nsBaseWidget.cpp | 6 +- widget/nsHTMLFormatConverter.cpp | 6 +- widget/nsNativeTheme.cpp | 16 +- widget/nsPrintSettingsService.cpp | 2 +- widget/windows/GfxInfo.cpp | 17 +- widget/windows/JumpListBuilder.cpp | 3 +- widget/windows/KeyboardLayout.cpp | 242 +-- widget/windows/LSPAnnotator.cpp | 2 +- widget/windows/TSFTextStore.cpp | 39 +- widget/windows/ToastNotificationHandler.cpp | 10 +- widget/windows/WinIMEHandler.cpp | 5 +- widget/windows/WinUtils.cpp | 8 +- widget/windows/WindowsSMTCProvider.cpp | 4 +- widget/windows/WindowsUIUtils.cpp | 7 +- widget/windows/nsAppShell.cpp | 2 +- widget/windows/nsClipboard.cpp | 10 +- widget/windows/nsDataObj.cpp | 11 +- widget/windows/nsDeviceContextSpecWin.cpp | 49 +- widget/windows/nsFilePicker.cpp | 5 +- widget/windows/nsLookAndFeel.cpp | 26 +- widget/windows/nsWindow.cpp | 8 +- xpcom/base/CycleCollectedJSContext.cpp | 8 +- xpcom/base/LogCommandLineHandler.cpp | 3 +- xpcom/base/nsCycleCollector.cpp | 12 +- xpcom/base/nsDumpUtils.cpp | 2 +- xpcom/base/nsIMemoryReporter.idl | 4 +- xpcom/base/nsMacUtilsImpl.cpp | 2 +- xpcom/base/nsMemoryInfoDumper.cpp | 21 +- xpcom/base/nsMemoryReporterManager.cpp | 10 +- xpcom/base/nsSystemInfo.cpp | 71 +- xpcom/build/LateWriteChecks.cpp | 2 +- xpcom/build/XPCOMInit.cpp | 2 +- xpcom/components/ManifestParser.cpp | 3 +- xpcom/components/gen_static_components.py | 2 +- xpcom/components/nsComponentManager.cpp | 26 +- xpcom/ds/nsAtomTable.cpp | 4 +- xpcom/ds/nsObserverService.cpp | 11 +- xpcom/io/FilePreferences.cpp | 6 +- xpcom/io/SpecialSystemDirectory.cpp | 2 +- xpcom/io/nsAppFileLocationProvider.cpp | 22 +- xpcom/io/nsLocalFileUnix.cpp | 4 +- xpcom/io/nsLocalFileWin.cpp | 4 +- xpcom/string/nsTLiteralString.h | 2 +- xpcom/tests/TestHarness.h | 4 +- xpcom/tests/gtest/TestAtoms.cpp | 2 +- xpcom/tests/gtest/TestDafsa.cpp | 20 +- xpcom/tests/gtest/TestEventTargetQI.cpp | 6 +- xpcom/tests/gtest/TestFile.cpp | 6 +- xpcom/tests/gtest/TestFilePreferencesUnix.cpp | 56 +- xpcom/tests/gtest/TestFilePreferencesWin.cpp | 160 +- xpcom/tests/gtest/TestHashtables.cpp | 14 +- .../tests/gtest/TestLogCommandLineHandler.cpp | 39 +- xpcom/tests/gtest/TestMruCache.cpp | 6 +- xpcom/tests/gtest/TestObserverService.cpp | 32 +- xpcom/tests/gtest/TestStrings.cpp | 149 +- xpcom/tests/gtest/TestSubstringTuple.cpp | 12 +- xpcom/tests/gtest/TestTextFormatter.cpp | 2 +- xpcom/tests/gtest/TestThreadMetrics.cpp | 4 +- xpcom/tests/gtest/TestTokenizer.cpp | 97 +- xpcom/tests/gtest/TestUTF.cpp | 16 +- xpcom/tests/windows/TestNtPathToDosPath.cpp | 2 +- xpcom/threads/CPUUsageWatcher.cpp | 2 +- xpcom/threads/nsThreadManager.cpp | 6 +- xpfe/appshell/AppWindow.cpp | 73 +- xpfe/appshell/nsAppShellWindowEnumerator.cpp | 2 +- xpfe/appshell/nsContentTreeOwner.cpp | 3 +- 1219 files changed, 10180 insertions(+), 12180 deletions(-) diff --git a/accessible/android/AccessibleWrap.cpp b/accessible/android/AccessibleWrap.cpp index 372696765c27..6a8828dd706f 100644 --- a/accessible/android/AccessibleWrap.cpp +++ b/accessible/android/AccessibleWrap.cpp @@ -538,7 +538,7 @@ void AccessibleWrap::GetRoleDescription(role aRole, if (aRole == roles::HEADING && aAttributes) { // The heading level is an attribute, so we need that. AutoTArray formatString; - nsresult rv = aAttributes->GetStringProperty(NS_LITERAL_CSTRING("level"), + nsresult rv = aAttributes->GetStringProperty("level"_ns, *formatString.AppendElement()); if (NS_SUCCEEDED(rv) && LocalizeString("headingLevel", aRoleDescription, formatString)) { @@ -548,8 +548,8 @@ void AccessibleWrap::GetRoleDescription(role aRole, if ((aRole == roles::LANDMARK || aRole == roles::REGION) && aAttributes) { nsAutoString xmlRoles; - if (NS_SUCCEEDED(aAttributes->GetStringProperty( - NS_LITERAL_CSTRING("xml-roles"), xmlRoles))) { + if (NS_SUCCEEDED( + aAttributes->GetStringProperty("xml-roles"_ns, xmlRoles))) { nsWhitespaceTokenizer tokenizer(xmlRoles); while (tokenizer.hasMoreTokens()) { if (LocalizeString(NS_ConvertUTF16toUTF8(tokenizer.nextToken()).get(), @@ -798,8 +798,7 @@ mozilla::java::GeckoBundle::LocalRef AccessibleWrap::ToBundle( } nsString posinset; - nsresult rv = aAttributes->GetStringProperty(NS_LITERAL_CSTRING("posinset"), - posinset); + nsresult rv = aAttributes->GetStringProperty("posinset"_ns, posinset); if (NS_SUCCEEDED(rv)) { int32_t rowIndex; if (sscanf(NS_ConvertUTF16toUTF8(posinset).get(), "%d", &rowIndex) > 0) { @@ -819,8 +818,7 @@ mozilla::java::GeckoBundle::LocalRef AccessibleWrap::ToBundle( } nsString colSize; - rv = aAttributes->GetStringProperty(NS_LITERAL_CSTRING("child-item-count"), - colSize); + rv = aAttributes->GetStringProperty("child-item-count"_ns, colSize); if (NS_SUCCEEDED(rv)) { int32_t rowCount; if (sscanf(NS_ConvertUTF16toUTF8(colSize).get(), "%d", &rowCount) > 0) { @@ -831,8 +829,7 @@ mozilla::java::GeckoBundle::LocalRef AccessibleWrap::ToBundle( java::sdk::Integer::ValueOf(1)); nsString unused; - rv = aAttributes->GetStringProperty(NS_LITERAL_CSTRING("hierarchical"), - unused); + rv = aAttributes->GetStringProperty("hierarchical"_ns, unused); if (NS_SUCCEEDED(rv)) { GECKOBUNDLE_PUT(collectionInfo, "isHierarchical", java::sdk::Boolean::TRUE()); @@ -897,8 +894,7 @@ bool AccessibleWrap::HandleLiveRegionEvent(AccEvent* aEvent) { nsCOMPtr attributes = Attributes(); nsString live; - nsresult rv = - attributes->GetStringProperty(NS_LITERAL_CSTRING("container-live"), live); + nsresult rv = attributes->GetStringProperty("container-live"_ns, live); if (!NS_SUCCEEDED(rv)) { return false; } @@ -908,8 +904,7 @@ bool AccessibleWrap::HandleLiveRegionEvent(AccEvent* aEvent) { : nsIAccessibleAnnouncementEvent::POLITE; nsString atomic; - rv = attributes->GetStringProperty(NS_LITERAL_CSTRING("container-atomic"), - atomic); + rv = attributes->GetStringProperty("container-atomic"_ns, atomic); Accessible* announcementTarget = this; nsAutoString announcement; diff --git a/accessible/aom/AccessibleNode.cpp b/accessible/aom/AccessibleNode.cpp index e353d633fcb7..0c00b411e40b 100644 --- a/accessible/aom/AccessibleNode.cpp +++ b/accessible/aom/AccessibleNode.cpp @@ -82,7 +82,7 @@ void AccessibleNode::GetComputedRole(nsAString& aRole) { void AccessibleNode::GetStates(nsTArray& aStates) { nsAccessibilityService* accService = GetOrCreateAccService(); if (!mIntl || !accService) { - aStates.AppendElement(NS_LITERAL_STRING("defunct")); + aStates.AppendElement(u"defunct"_ns); return; } diff --git a/accessible/atk/Platform.cpp b/accessible/atk/Platform.cpp index 9d877bab1c32..64c8ae844068 100644 --- a/accessible/atk/Platform.cpp +++ b/accessible/atk/Platform.cpp @@ -315,11 +315,10 @@ bool a11y::ShouldA11yBeEnabled() { nsCOMPtr a11y_settings; if (gsettings) { - gsettings->GetCollectionForSchema( - NS_LITERAL_CSTRING(GSETINGS_A11Y_INTERFACE), - getter_AddRefs(a11y_settings)); + gsettings->GetCollectionForSchema(nsLiteralCString(GSETINGS_A11Y_INTERFACE), + getter_AddRefs(a11y_settings)); if (a11y_settings) { - a11y_settings->GetBoolean(NS_LITERAL_CSTRING(GSETINGS_A11Y_KEY), + a11y_settings->GetBoolean(nsLiteralCString(GSETINGS_A11Y_KEY), &sShouldEnable); } } diff --git a/accessible/base/ARIAMap.cpp b/accessible/base/ARIAMap.cpp index 18770ff365b4..a19fe904f389 100644 --- a/accessible/base/ARIAMap.cpp +++ b/accessible/base/ARIAMap.cpp @@ -1469,8 +1469,7 @@ bool AttrIterator::Next(nsAString& aAttrName, nsAString& aAttrValue) { if (attr->NamespaceEquals(kNameSpaceID_None)) { nsAtom* attrAtom = attr->Atom(); nsDependentAtomString attrStr(attrAtom); - if (!StringBeginsWith(attrStr, NS_LITERAL_STRING("aria-"))) - continue; // Not ARIA + if (!StringBeginsWith(attrStr, u"aria-"_ns)) continue; // Not ARIA uint8_t attrFlags = aria::AttrCharacteristicsFor(attrAtom); if (attrFlags & ATTR_BYPASSOBJ) diff --git a/accessible/base/DocManager.cpp b/accessible/base/DocManager.cpp index b3a3736a6eb8..6c561a7c743f 100644 --- a/accessible/base/DocManager.cpp +++ b/accessible/base/DocManager.cpp @@ -387,8 +387,7 @@ void DocManager::AddListeners(Document* aDocument, nsPIDOMWindowOuter* window = aDocument->GetWindow(); EventTarget* target = window->GetChromeEventHandler(); EventListenerManager* elm = target->GetOrCreateListenerManager(); - elm->AddEventListenerByType(this, NS_LITERAL_STRING("pagehide"), - TrustedEventsAtCapture()); + elm->AddEventListenerByType(this, u"pagehide"_ns, TrustedEventsAtCapture()); #ifdef A11Y_LOG if (logging::IsEnabled(logging::eDocCreate)) @@ -396,7 +395,7 @@ void DocManager::AddListeners(Document* aDocument, #endif if (aAddDOMContentLoadedListener) { - elm->AddEventListenerByType(this, NS_LITERAL_STRING("DOMContentLoaded"), + elm->AddEventListenerByType(this, u"DOMContentLoaded"_ns, TrustedEventsAtCapture()); #ifdef A11Y_LOG if (logging::IsEnabled(logging::eDocCreate)) @@ -413,10 +412,10 @@ void DocManager::RemoveListeners(Document* aDocument) { if (!target) return; EventListenerManager* elm = target->GetOrCreateListenerManager(); - elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("pagehide"), + elm->RemoveEventListenerByType(this, u"pagehide"_ns, TrustedEventsAtCapture()); - elm->RemoveEventListenerByType(this, NS_LITERAL_STRING("DOMContentLoaded"), + elm->RemoveEventListenerByType(this, u"DOMContentLoaded"_ns, TrustedEventsAtCapture()); } diff --git a/accessible/base/MarkupMap.h b/accessible/base/MarkupMap.h index 51aaf5503905..1a0e06cf87c9 100644 --- a/accessible/base/MarkupMap.h +++ b/accessible/base/MarkupMap.h @@ -80,8 +80,7 @@ MARKUPMAP( nsAutoString displayValue; StyleInfo styleInfo(aElement); styleInfo.Display(displayValue); - if (displayValue != NS_LITERAL_STRING("block") && - displayValue != NS_LITERAL_STRING("inline-block")) { + if (displayValue != u"block"_ns && displayValue != u"inline-block"_ns) { return nullptr; } // Check for various conditions to determine if this is a block diff --git a/accessible/base/TextAttrs.cpp b/accessible/base/TextAttrs.cpp index 7e9495ca1f1a..2b6bd4d5e577 100644 --- a/accessible/base/TextAttrs.cpp +++ b/accessible/base/TextAttrs.cpp @@ -237,23 +237,19 @@ void TextAttrsMgr::InvalidTextAttr::ExposeValue( nsIPersistentProperties* aAttributes, const uint32_t& aValue) { switch (aValue) { case eFalse: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, - NS_LITERAL_STRING("false")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"false"_ns); break; case eGrammar: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, - NS_LITERAL_STRING("grammar")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"grammar"_ns); break; case eSpelling: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, - NS_LITERAL_STRING("spelling")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"spelling"_ns); break; case eTrue: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, - NS_LITERAL_STRING("true")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"true"_ns); break; } } @@ -592,9 +588,8 @@ bool TextAttrsMgr::AutoGeneratedTextAttr::GetValueFor(Accessible* aAccessible, void TextAttrsMgr::AutoGeneratedTextAttr::ExposeValue( nsIPersistentProperties* aAttributes, const bool& aValue) { - nsAccUtils::SetAccAttr( - aAttributes, nsGkAtoms::auto_generated, - aValue ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::auto_generated, + aValue ? u"true"_ns : u"false"_ns); } //////////////////////////////////////////////////////////////////////////////// @@ -697,17 +692,15 @@ void TextAttrsMgr::TextPosTextAttr::ExposeValue( switch (aValue) { case eTextPosBaseline: nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textPosition, - NS_LITERAL_STRING("baseline")); + u"baseline"_ns); break; case eTextPosSub: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textPosition, - NS_LITERAL_STRING("sub")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textPosition, u"sub"_ns); break; case eTextPosSuper: - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textPosition, - NS_LITERAL_STRING("super")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::textPosition, u"super"_ns); break; case eTextPosNone: diff --git a/accessible/base/XULMap.h b/accessible/base/XULMap.h index da0f68d984f1..57ba95e0fdd1 100644 --- a/accessible/base/XULMap.h +++ b/accessible/base/XULMap.h @@ -38,7 +38,7 @@ XULMAP_TYPE(toolbarbutton, XULToolbarButtonAccessible) XULMAP_TYPE(tooltip, XULTooltipAccessible) XULMAP(label, [](Element* aElement, Accessible* aContext) -> Accessible* { - if (aElement->ClassList()->Contains(NS_LITERAL_STRING("text-link"))) { + if (aElement->ClassList()->Contains(u"text-link"_ns)) { return new XULLinkAccessible(aElement, aContext->Document()); } return new XULLabelAccessible(aElement, aContext->Document()); diff --git a/accessible/base/nsAccUtils.cpp b/accessible/base/nsAccUtils.cpp index e39eb2fd2de2..4fa5247812fb 100644 --- a/accessible/base/nsAccUtils.cpp +++ b/accessible/base/nsAccUtils.cpp @@ -161,8 +161,7 @@ void nsAccUtils::SetLiveContainerAttributes( if (ancestor->IsElement() && ancestor->AsElement()->AttrValueIs( kNameSpaceID_None, nsGkAtoms::aria_atomic, nsGkAtoms::_true, eCaseMatters)) { - SetAccAttr(aAttributes, nsGkAtoms::containerAtomic, - NS_LITERAL_STRING("true")); + SetAccAttr(aAttributes, nsGkAtoms::containerAtomic, u"true"_ns); } // container-busy attribute @@ -357,10 +356,10 @@ nsIntPoint nsAccUtils::GetScreenCoordsForParent(Accessible* aAccessible) { bool nsAccUtils::GetLiveAttrValue(uint32_t aRule, nsAString& aValue) { switch (aRule) { case eOffLiveAttr: - aValue = NS_LITERAL_STRING("off"); + aValue = u"off"_ns; return true; case ePoliteLiveAttr: - aValue = NS_LITERAL_STRING("polite"); + aValue = u"polite"_ns; return true; } diff --git a/accessible/base/nsAccessibilityService.cpp b/accessible/base/nsAccessibilityService.cpp index 8e1388e172df..86944a2cd24b 100644 --- a/accessible/base/nsAccessibilityService.cpp +++ b/accessible/base/nsAccessibilityService.cpp @@ -123,8 +123,7 @@ static bool MustBeAccessible(nsIContent* aContent, DocAccessible* aDocument) { } nsDependentAtomString attrStr(attrAtom); - if (!StringBeginsWith(attrStr, NS_LITERAL_STRING("aria-"))) - continue; // not ARIA + if (!StringBeginsWith(attrStr, u"aria-"_ns)) continue; // not ARIA // A global state or a property and in case of token defined. uint8_t attrFlags = aria::AttrCharacteristicsFor(attrAtom); @@ -702,7 +701,7 @@ void nsAccessibilityService::GetStringStates(uint32_t aState, // unknown state if (!stringStates->Length()) { - stringStates->Add(NS_LITERAL_STRING("unknown")); + stringStates->Add(u"unknown"_ns); } stringStates.forget(aStringStates); @@ -713,148 +712,148 @@ already_AddRefed nsAccessibilityService::GetStringStates( RefPtr stringStates = new DOMStringList(); if (aStates & states::UNAVAILABLE) { - stringStates->Add(NS_LITERAL_STRING("unavailable")); + stringStates->Add(u"unavailable"_ns); } if (aStates & states::SELECTED) { - stringStates->Add(NS_LITERAL_STRING("selected")); + stringStates->Add(u"selected"_ns); } if (aStates & states::FOCUSED) { - stringStates->Add(NS_LITERAL_STRING("focused")); + stringStates->Add(u"focused"_ns); } if (aStates & states::PRESSED) { - stringStates->Add(NS_LITERAL_STRING("pressed")); + stringStates->Add(u"pressed"_ns); } if (aStates & states::CHECKED) { - stringStates->Add(NS_LITERAL_STRING("checked")); + stringStates->Add(u"checked"_ns); } if (aStates & states::MIXED) { - stringStates->Add(NS_LITERAL_STRING("mixed")); + stringStates->Add(u"mixed"_ns); } if (aStates & states::READONLY) { - stringStates->Add(NS_LITERAL_STRING("readonly")); + stringStates->Add(u"readonly"_ns); } if (aStates & states::HOTTRACKED) { - stringStates->Add(NS_LITERAL_STRING("hottracked")); + stringStates->Add(u"hottracked"_ns); } if (aStates & states::DEFAULT) { - stringStates->Add(NS_LITERAL_STRING("default")); + stringStates->Add(u"default"_ns); } if (aStates & states::EXPANDED) { - stringStates->Add(NS_LITERAL_STRING("expanded")); + stringStates->Add(u"expanded"_ns); } if (aStates & states::COLLAPSED) { - stringStates->Add(NS_LITERAL_STRING("collapsed")); + stringStates->Add(u"collapsed"_ns); } if (aStates & states::BUSY) { - stringStates->Add(NS_LITERAL_STRING("busy")); + stringStates->Add(u"busy"_ns); } if (aStates & states::FLOATING) { - stringStates->Add(NS_LITERAL_STRING("floating")); + stringStates->Add(u"floating"_ns); } if (aStates & states::ANIMATED) { - stringStates->Add(NS_LITERAL_STRING("animated")); + stringStates->Add(u"animated"_ns); } if (aStates & states::INVISIBLE) { - stringStates->Add(NS_LITERAL_STRING("invisible")); + stringStates->Add(u"invisible"_ns); } if (aStates & states::OFFSCREEN) { - stringStates->Add(NS_LITERAL_STRING("offscreen")); + stringStates->Add(u"offscreen"_ns); } if (aStates & states::SIZEABLE) { - stringStates->Add(NS_LITERAL_STRING("sizeable")); + stringStates->Add(u"sizeable"_ns); } if (aStates & states::MOVEABLE) { - stringStates->Add(NS_LITERAL_STRING("moveable")); + stringStates->Add(u"moveable"_ns); } if (aStates & states::SELFVOICING) { - stringStates->Add(NS_LITERAL_STRING("selfvoicing")); + stringStates->Add(u"selfvoicing"_ns); } if (aStates & states::FOCUSABLE) { - stringStates->Add(NS_LITERAL_STRING("focusable")); + stringStates->Add(u"focusable"_ns); } if (aStates & states::SELECTABLE) { - stringStates->Add(NS_LITERAL_STRING("selectable")); + stringStates->Add(u"selectable"_ns); } if (aStates & states::LINKED) { - stringStates->Add(NS_LITERAL_STRING("linked")); + stringStates->Add(u"linked"_ns); } if (aStates & states::TRAVERSED) { - stringStates->Add(NS_LITERAL_STRING("traversed")); + stringStates->Add(u"traversed"_ns); } if (aStates & states::MULTISELECTABLE) { - stringStates->Add(NS_LITERAL_STRING("multiselectable")); + stringStates->Add(u"multiselectable"_ns); } if (aStates & states::EXTSELECTABLE) { - stringStates->Add(NS_LITERAL_STRING("extselectable")); + stringStates->Add(u"extselectable"_ns); } if (aStates & states::PROTECTED) { - stringStates->Add(NS_LITERAL_STRING("protected")); + stringStates->Add(u"protected"_ns); } if (aStates & states::HASPOPUP) { - stringStates->Add(NS_LITERAL_STRING("haspopup")); + stringStates->Add(u"haspopup"_ns); } if (aStates & states::REQUIRED) { - stringStates->Add(NS_LITERAL_STRING("required")); + stringStates->Add(u"required"_ns); } if (aStates & states::ALERT) { - stringStates->Add(NS_LITERAL_STRING("alert")); + stringStates->Add(u"alert"_ns); } if (aStates & states::INVALID) { - stringStates->Add(NS_LITERAL_STRING("invalid")); + stringStates->Add(u"invalid"_ns); } if (aStates & states::CHECKABLE) { - stringStates->Add(NS_LITERAL_STRING("checkable")); + stringStates->Add(u"checkable"_ns); } if (aStates & states::SUPPORTS_AUTOCOMPLETION) { - stringStates->Add(NS_LITERAL_STRING("autocompletion")); + stringStates->Add(u"autocompletion"_ns); } if (aStates & states::DEFUNCT) { - stringStates->Add(NS_LITERAL_STRING("defunct")); + stringStates->Add(u"defunct"_ns); } if (aStates & states::SELECTABLE_TEXT) { - stringStates->Add(NS_LITERAL_STRING("selectable text")); + stringStates->Add(u"selectable text"_ns); } if (aStates & states::EDITABLE) { - stringStates->Add(NS_LITERAL_STRING("editable")); + stringStates->Add(u"editable"_ns); } if (aStates & states::ACTIVE) { - stringStates->Add(NS_LITERAL_STRING("active")); + stringStates->Add(u"active"_ns); } if (aStates & states::MODAL) { - stringStates->Add(NS_LITERAL_STRING("modal")); + stringStates->Add(u"modal"_ns); } if (aStates & states::MULTI_LINE) { - stringStates->Add(NS_LITERAL_STRING("multi line")); + stringStates->Add(u"multi line"_ns); } if (aStates & states::HORIZONTAL) { - stringStates->Add(NS_LITERAL_STRING("horizontal")); + stringStates->Add(u"horizontal"_ns); } if (aStates & states::OPAQUE1) { - stringStates->Add(NS_LITERAL_STRING("opaque")); + stringStates->Add(u"opaque"_ns); } if (aStates & states::SINGLE_LINE) { - stringStates->Add(NS_LITERAL_STRING("single line")); + stringStates->Add(u"single line"_ns); } if (aStates & states::TRANSIENT) { - stringStates->Add(NS_LITERAL_STRING("transient")); + stringStates->Add(u"transient"_ns); } if (aStates & states::VERTICAL) { - stringStates->Add(NS_LITERAL_STRING("vertical")); + stringStates->Add(u"vertical"_ns); } if (aStates & states::STALE) { - stringStates->Add(NS_LITERAL_STRING("stale")); + stringStates->Add(u"stale"_ns); } if (aStates & states::ENABLED) { - stringStates->Add(NS_LITERAL_STRING("enabled")); + stringStates->Add(u"enabled"_ns); } if (aStates & states::SENSITIVE) { - stringStates->Add(NS_LITERAL_STRING("sensitive")); + stringStates->Add(u"sensitive"_ns); } if (aStates & states::PINNED) { - stringStates->Add(NS_LITERAL_STRING("pinned")); + stringStates->Add(u"pinned"_ns); } if (aStates & states::CURRENT) { - stringStates->Add(NS_LITERAL_STRING("current")); + stringStates->Add(u"current"_ns); } return stringStates.forget(); @@ -1280,7 +1279,7 @@ bool nsAccessibilityService::Init() { gApplicationAccessible->Init(); CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::Accessibility, - NS_LITERAL_CSTRING("Active")); + "Active"_ns); #ifdef XP_WIN sPendingPlugins = new nsTArray >; diff --git a/accessible/base/nsEventShell.cpp b/accessible/base/nsEventShell.cpp index de49b5bac1f7..d158102a79ba 100644 --- a/accessible/base/nsEventShell.cpp +++ b/accessible/base/nsEventShell.cpp @@ -61,8 +61,7 @@ void nsEventShell::GetEventAttributes(nsINode* aNode, if (aNode != sEventTargetNode) return; nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::eventFromInput, - sEventFromUserInput ? NS_LITERAL_STRING("true") - : NS_LITERAL_STRING("false")); + sEventFromUserInput ? u"true"_ns : u"false"_ns); } //////////////////////////////////////////////////////////////////////////////// diff --git a/accessible/generic/ARIAGridAccessible.cpp b/accessible/generic/ARIAGridAccessible.cpp index 055bcde5de73..b70f07d9d331 100644 --- a/accessible/generic/ARIAGridAccessible.cpp +++ b/accessible/generic/ARIAGridAccessible.cpp @@ -42,8 +42,7 @@ ARIAGridAccessible::NativeAttributes() { if (IsProbablyLayoutTable()) { nsAutoString unused; - attributes->SetStringProperty(NS_LITERAL_CSTRING("layout-guess"), - NS_LITERAL_STRING("true"), unused); + attributes->SetStringProperty("layout-guess"_ns, u"true"_ns, unused); } return attributes.forget(); @@ -385,13 +384,11 @@ nsresult ARIAGridAccessible::SetARIASelected(Accessible* aAccessible, nsresult rv = NS_OK; if (content->IsElement()) { if (aIsSelected) - rv = content->AsElement()->SetAttr(kNameSpaceID_None, - nsGkAtoms::aria_selected, - NS_LITERAL_STRING("true"), aNotify); + rv = content->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"true"_ns, aNotify); else - rv = content->AsElement()->SetAttr(kNameSpaceID_None, - nsGkAtoms::aria_selected, - NS_LITERAL_STRING("false"), aNotify); + rv = content->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"false"_ns, aNotify); } NS_ENSURE_SUCCESS(rv, rv); @@ -608,8 +605,7 @@ ARIAGridCellAccessible::NativeAttributes() { #ifdef DEBUG nsAutoString unused; - attributes->SetStringProperty(NS_LITERAL_CSTRING("cppclass"), - NS_LITERAL_STRING("ARIAGridCellAccessible"), + attributes->SetStringProperty("cppclass"_ns, u"ARIAGridCellAccessible"_ns, unused); #endif diff --git a/accessible/generic/Accessible.cpp b/accessible/generic/Accessible.cpp index fbf5cd30f190..93d986d78c4c 100644 --- a/accessible/generic/Accessible.cpp +++ b/accessible/generic/Accessible.cpp @@ -675,9 +675,8 @@ void Accessible::SetSelected(bool aSelect) { if (select->State() & states::MULTISELECTABLE) { if (mContent->IsElement() && ARIARoleMap()) { if (aSelect) { - mContent->AsElement()->SetAttr(kNameSpaceID_None, - nsGkAtoms::aria_selected, - NS_LITERAL_STRING("true"), true); + mContent->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"true"_ns, true); } else { mContent->AsElement()->UnsetAttr(kNameSpaceID_None, nsGkAtoms::aria_selected, true); @@ -957,7 +956,7 @@ already_AddRefed Accessible::Attributes() { if (roleMapEntry) { if (roleMapEntry->Is(nsGkAtoms::searchbox)) { nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textInputType, - NS_LITERAL_STRING("search")); + u"search"_ns); } nsAutoString live; @@ -983,21 +982,18 @@ already_AddRefed Accessible::NativeAttributes() { if (HasNumericValue()) { nsAutoString valuetext; Value(valuetext); - attributes->SetStringProperty(NS_LITERAL_CSTRING("valuetext"), valuetext, - unused); + attributes->SetStringProperty("valuetext"_ns, valuetext, unused); } // Expose checkable object attribute if the accessible has checkable state if (State() & states::CHECKABLE) { - nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable, - NS_LITERAL_STRING("true")); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable, u"true"_ns); } // Expose 'explicit-name' attribute. nsAutoString name; if (Name(name) != eNameFromSubtree && !name.IsVoid()) { - attributes->SetStringProperty(NS_LITERAL_CSTRING("explicit-name"), - NS_LITERAL_STRING("true"), unused); + attributes->SetStringProperty("explicit-name"_ns, u"true"_ns, unused); } // Group attributes (level/setsize/posinset) @@ -1010,13 +1006,11 @@ already_AddRefed Accessible::NativeAttributes() { if (itemCount) { nsAutoString itemCountStr; itemCountStr.AppendInt(itemCount); - attributes->SetStringProperty(NS_LITERAL_CSTRING("child-item-count"), - itemCountStr, unused); + attributes->SetStringProperty("child-item-count"_ns, itemCountStr, unused); } if (hierarchical) { - attributes->SetStringProperty(NS_LITERAL_CSTRING("hierarchical"), - NS_LITERAL_STRING("true"), unused); + attributes->SetStringProperty("hierarchical"_ns, u"true"_ns, unused); } // If the accessible doesn't have own content (such as list item bullet or @@ -1035,7 +1029,7 @@ already_AddRefed Accessible::NativeAttributes() { nsAutoString id; if (nsCoreUtils::GetID(mContent, id)) - attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, unused); + attributes->SetStringProperty("id"_ns, id, unused); // Expose class because it may have useful microformat information. nsAutoString _class; @@ -1051,8 +1045,7 @@ already_AddRefed Accessible::NativeAttributes() { // Expose draggable object attribute. if (auto htmlElement = nsGenericHTMLElement::FromNode(mContent)) { if (htmlElement->Draggable()) { - nsAccUtils::SetAccAttr(attributes, nsGkAtoms::draggable, - NS_LITERAL_STRING("true")); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::draggable, u"true"_ns); } } @@ -1759,8 +1752,7 @@ Relation Accessible::RelationByType(RelationType aType) const { nsIContent* buttonEl = nullptr; if (doc->AllowXULXBL()) { nsCOMPtr possibleDefaultButtons = - doc->GetElementsByAttribute(NS_LITERAL_STRING("default"), - NS_LITERAL_STRING("true")); + doc->GetElementsByAttribute(u"default"_ns, u"true"_ns); if (possibleDefaultButtons) { uint32_t length = possibleDefaultButtons->Length(); // Check for button in list of default="true" elements diff --git a/accessible/generic/DocAccessible.cpp b/accessible/generic/DocAccessible.cpp index 16ba64ee7aa3..104dca82c322 100644 --- a/accessible/generic/DocAccessible.cpp +++ b/accessible/generic/DocAccessible.cpp @@ -824,8 +824,7 @@ void DocAccessible::AttributeChangedImpl(Accessible* aAccessible, // Check for namespaced ARIA attribute if (aNameSpaceID == kNameSpaceID_None) { // Check for hyphenated aria-foo property? - if (StringBeginsWith(nsDependentAtomString(aAttribute), - NS_LITERAL_STRING("aria-"))) { + if (StringBeginsWith(nsDependentAtomString(aAttribute), u"aria-"_ns)) { ARIAAttributeChanged(aAccessible, aAttribute); } } diff --git a/accessible/generic/HyperTextAccessible.cpp b/accessible/generic/HyperTextAccessible.cpp index 96d72f59bf64..2b0b1701b3c8 100644 --- a/accessible/generic/HyperTextAccessible.cpp +++ b/accessible/generic/HyperTextAccessible.cpp @@ -1062,8 +1062,7 @@ HyperTextAccessible::NativeAttributes() { nsIFrame* frame = GetFrame(); if (frame && frame->IsBlockFrame()) { nsAutoString unused; - attributes->SetStringProperty(NS_LITERAL_CSTRING("formatting"), - NS_LITERAL_STRING("block"), unused); + attributes->SetStringProperty("formatting"_ns, u"block"_ns, unused); } if (FocusMgr()->IsFocused(this)) { @@ -2056,8 +2055,7 @@ void HyperTextAccessible::GetSpellTextAttr( if (endOffset < *aEndOffset) *aEndOffset = endOffset; if (aAttributes) { - nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, - NS_LITERAL_STRING("spelling")); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"spelling"_ns); } return; diff --git a/accessible/generic/RootAccessible.cpp b/accessible/generic/RootAccessible.cpp index d4f78cbff761..8d440e2c7c35 100644 --- a/accessible/generic/RootAccessible.cpp +++ b/accessible/generic/RootAccessible.cpp @@ -667,10 +667,10 @@ void RootAccessible::HandleTreeRowCountChangedEvent( nsresult rv; int32_t index, count; - rv = propBag->GetPropertyAsInt32(NS_LITERAL_STRING("index"), &index); + rv = propBag->GetPropertyAsInt32(u"index"_ns, &index); if (NS_FAILED(rv)) return; - rv = propBag->GetPropertyAsInt32(NS_LITERAL_STRING("count"), &count); + rv = propBag->GetPropertyAsInt32(u"count"_ns, &count); if (NS_FAILED(rv)) return; aAccessible->InvalidateCache(index, count); @@ -683,10 +683,10 @@ void RootAccessible::HandleTreeInvalidatedEvent( if (!propBag) return; int32_t startRow = 0, endRow = -1, startCol = 0, endCol = -1; - propBag->GetPropertyAsInt32(NS_LITERAL_STRING("startrow"), &startRow); - propBag->GetPropertyAsInt32(NS_LITERAL_STRING("endrow"), &endRow); - propBag->GetPropertyAsInt32(NS_LITERAL_STRING("startcolumn"), &startCol); - propBag->GetPropertyAsInt32(NS_LITERAL_STRING("endcolumn"), &endCol); + propBag->GetPropertyAsInt32(u"startrow"_ns, &startRow); + propBag->GetPropertyAsInt32(u"endrow"_ns, &endRow); + propBag->GetPropertyAsInt32(u"startcolumn"_ns, &startCol); + propBag->GetPropertyAsInt32(u"endcolumn"_ns, &endCol); aAccessible->TreeViewInvalidated(startRow, endRow, startCol, endCol); } diff --git a/accessible/generic/TableAccessible.cpp b/accessible/generic/TableAccessible.cpp index f9329199906b..17c7b07b45cd 100644 --- a/accessible/generic/TableAccessible.cpp +++ b/accessible/generic/TableAccessible.cpp @@ -28,12 +28,12 @@ bool TableAccessible::IsProbablyLayoutTable() { // the algorithm. Integrate it into Logging. // Change to |#define SHOW_LAYOUT_HEURISTIC DEBUG| before final release #ifdef SHOW_LAYOUT_HEURISTIC -# define RETURN_LAYOUT_ANSWER(isLayout, heuristic) \ - { \ - mLayoutHeuristic = isLayout \ - ? NS_LITERAL_STRING("layout table: " heuristic) \ - : NS_LITERAL_STRING("data table: " heuristic); \ - return isLayout; \ +# define RETURN_LAYOUT_ANSWER(isLayout, heuristic) \ + { \ + mLayoutHeuristic = isLayout \ + ? nsLiteralString(u"layout table: " heuristic) \ + : nsLiteralString(u"data table: " heuristic); \ + return isLayout; \ } #else # define RETURN_LAYOUT_ANSWER(isLayout, heuristic) \ @@ -64,8 +64,8 @@ bool TableAccessible::IsProbablyLayoutTable() { "Table should not be built by CSS display:table style"); // Check if datatable attribute has "0" value. - if (el->AttrValueIs(kNameSpaceID_None, nsGkAtoms::datatable, - NS_LITERAL_STRING("0"), eCaseMatters)) { + if (el->AttrValueIs(kNameSpaceID_None, nsGkAtoms::datatable, u"0"_ns, + eCaseMatters)) { RETURN_LAYOUT_ANSWER(true, "Has datatable = 0 attribute, it's for layout"); } @@ -130,7 +130,7 @@ bool TableAccessible::IsProbablyLayoutTable() { // Check for nested tables. nsCOMPtr nestedTables = - el->GetElementsByTagName(NS_LITERAL_STRING("table")); + el->GetElementsByTagName(u"table"_ns); if (nestedTables->Length() > 0) { RETURN_LAYOUT_ANSWER(true, "Has a nested table within it"); } @@ -222,9 +222,8 @@ bool TableAccessible::IsProbablyLayoutTable() { RETURN_LAYOUT_ANSWER(true, "2-4 columns, 10 cells or less, non-bordered"); } - static const nsLiteralString tags[] = {NS_LITERAL_STRING("embed"), - NS_LITERAL_STRING("object"), - NS_LITERAL_STRING("iframe")}; + static const nsLiteralString tags[] = {u"embed"_ns, u"object"_ns, + u"iframe"_ns}; for (auto& tag : tags) { nsCOMPtr descendants = el->GetElementsByTagName(tag); if (descendants->Length() > 0) { diff --git a/accessible/html/HTMLFormControlAccessible.cpp b/accessible/html/HTMLFormControlAccessible.cpp index 47b117c070ee..379308cc1f3e 100644 --- a/accessible/html/HTMLFormControlAccessible.cpp +++ b/accessible/html/HTMLFormControlAccessible.cpp @@ -249,8 +249,7 @@ HTMLTextFieldAccessible::NativeAttributes() { type)) { nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textInputType, type); if (!ARIARoleMap() && type.EqualsLiteral("search")) { - nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, - NS_LITERAL_STRING("searchbox")); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, u"searchbox"_ns); } } diff --git a/accessible/html/HTMLFormControlAccessible.h b/accessible/html/HTMLFormControlAccessible.h index b41deba38a00..2dc00e4837a8 100644 --- a/accessible/html/HTMLFormControlAccessible.h +++ b/accessible/html/HTMLFormControlAccessible.h @@ -114,7 +114,7 @@ class HTMLTextFieldAccessible : public HyperTextAccessibleWrap { return el; } // XUL search-textbox custom element - return Elm()->Closest(NS_LITERAL_STRING("search-textbox"), IgnoreErrors()); + return Elm()->Closest(u"search-textbox"_ns, IgnoreErrors()); } }; diff --git a/accessible/html/HTMLSelectAccessible.cpp b/accessible/html/HTMLSelectAccessible.cpp index 13f4934daae8..4dc6c4dade34 100644 --- a/accessible/html/HTMLSelectAccessible.cpp +++ b/accessible/html/HTMLSelectAccessible.cpp @@ -90,7 +90,7 @@ void HTMLSelectListAccessible::SetCurrentItem(const Accessible* aItem) { if (!aItem->GetContent()->IsElement()) return; aItem->GetContent()->AsElement()->SetAttr( - kNameSpaceID_None, nsGkAtoms::selected, NS_LITERAL_STRING("true"), true); + kNameSpaceID_None, nsGkAtoms::selected, u"true"_ns, true); } bool HTMLSelectListAccessible::IsAcceptableChild(nsIContent* aEl) const { diff --git a/accessible/html/HTMLTableAccessible.cpp b/accessible/html/HTMLTableAccessible.cpp index 456813b4bb2f..65eb6bf614d6 100644 --- a/accessible/html/HTMLTableAccessible.cpp +++ b/accessible/html/HTMLTableAccessible.cpp @@ -118,8 +118,7 @@ HTMLTableCellAccessible::NativeAttributes() { #ifdef DEBUG nsAutoString unused; - attributes->SetStringProperty(NS_LITERAL_CSTRING("cppclass"), - NS_LITERAL_STRING("HTMLTableCellAccessible"), + attributes->SetStringProperty("cppclass"_ns, u"HTMLTableCellAccessible"_ns, unused); #endif @@ -396,8 +395,7 @@ HTMLTableAccessible::NativeAttributes() { if (IsProbablyLayoutTable()) { nsAutoString unused; - attributes->SetStringProperty(NS_LITERAL_CSTRING("layout-guess"), - NS_LITERAL_STRING("true"), unused); + attributes->SetStringProperty("layout-guess"_ns, u"true"_ns, unused); } return attributes.forget(); diff --git a/accessible/mac/mozAccessible.mm b/accessible/mac/mozAccessible.mm index e2ec75ef042b..46da2079f8cf 100644 --- a/accessible/mac/mozAccessible.mm +++ b/accessible/mac/mozAccessible.mm @@ -462,34 +462,33 @@ - (NSString*)moxSubrole { const nsString description; }; -static const RoleDescrMap sRoleDescrMap[] = { - {@"AXApplicationAlert", NS_LITERAL_STRING("alert")}, - {@"AXApplicationAlertDialog", NS_LITERAL_STRING("alertDialog")}, - {@"AXApplicationDialog", NS_LITERAL_STRING("dialog")}, - {@"AXApplicationLog", NS_LITERAL_STRING("log")}, - {@"AXApplicationMarquee", NS_LITERAL_STRING("marquee")}, - {@"AXApplicationStatus", NS_LITERAL_STRING("status")}, - {@"AXApplicationTimer", NS_LITERAL_STRING("timer")}, - {@"AXContentSeparator", NS_LITERAL_STRING("separator")}, - {@"AXDefinition", NS_LITERAL_STRING("definition")}, - {@"AXDetails", NS_LITERAL_STRING("details")}, - {@"AXDocument", NS_LITERAL_STRING("document")}, - {@"AXDocumentArticle", NS_LITERAL_STRING("article")}, - {@"AXDocumentMath", NS_LITERAL_STRING("math")}, - {@"AXDocumentNote", NS_LITERAL_STRING("note")}, - {@"AXLandmarkApplication", NS_LITERAL_STRING("application")}, - {@"AXLandmarkBanner", NS_LITERAL_STRING("banner")}, - {@"AXLandmarkComplementary", NS_LITERAL_STRING("complementary")}, - {@"AXLandmarkContentInfo", NS_LITERAL_STRING("content")}, - {@"AXLandmarkMain", NS_LITERAL_STRING("main")}, - {@"AXLandmarkNavigation", NS_LITERAL_STRING("navigation")}, - {@"AXLandmarkRegion", NS_LITERAL_STRING("region")}, - {@"AXLandmarkSearch", NS_LITERAL_STRING("search")}, - {@"AXSearchField", NS_LITERAL_STRING("searchTextField")}, - {@"AXSummary", NS_LITERAL_STRING("summary")}, - {@"AXTabPanel", NS_LITERAL_STRING("tabPanel")}, - {@"AXTerm", NS_LITERAL_STRING("term")}, - {@"AXUserInterfaceTooltip", NS_LITERAL_STRING("tooltip")}}; +static const RoleDescrMap sRoleDescrMap[] = {{@"AXApplicationAlert", u"alert"_ns}, + {@"AXApplicationAlertDialog", u"alertDialog"_ns}, + {@"AXApplicationDialog", u"dialog"_ns}, + {@"AXApplicationLog", u"log"_ns}, + {@"AXApplicationMarquee", u"marquee"_ns}, + {@"AXApplicationStatus", u"status"_ns}, + {@"AXApplicationTimer", u"timer"_ns}, + {@"AXContentSeparator", u"separator"_ns}, + {@"AXDefinition", u"definition"_ns}, + {@"AXDetails", u"details"_ns}, + {@"AXDocument", u"document"_ns}, + {@"AXDocumentArticle", u"article"_ns}, + {@"AXDocumentMath", u"math"_ns}, + {@"AXDocumentNote", u"note"_ns}, + {@"AXLandmarkApplication", u"application"_ns}, + {@"AXLandmarkBanner", u"banner"_ns}, + {@"AXLandmarkComplementary", u"complementary"_ns}, + {@"AXLandmarkContentInfo", u"content"_ns}, + {@"AXLandmarkMain", u"main"_ns}, + {@"AXLandmarkNavigation", u"navigation"_ns}, + {@"AXLandmarkRegion", u"region"_ns}, + {@"AXLandmarkSearch", u"search"_ns}, + {@"AXSearchField", u"searchTextField"_ns}, + {@"AXSummary", u"summary"_ns}, + {@"AXTabPanel", u"tabPanel"_ns}, + {@"AXTerm", u"term"_ns}, + {@"AXUserInterfaceTooltip", u"tooltip"_ns}}; struct RoleDescrComparator { const NSString* mRole; @@ -498,14 +497,14 @@ explicit RoleDescrComparator(const NSString* aRole) : mRole(aRole) {} }; - (NSString*)moxRoleDescription { - if (mRole == roles::DOCUMENT) return utils::LocalizedString(NS_LITERAL_STRING("htmlContent")); + if (mRole == roles::DOCUMENT) return utils::LocalizedString(u"htmlContent"_ns); - if (mRole == roles::FIGURE) return utils::LocalizedString(NS_LITERAL_STRING("figure")); + if (mRole == roles::FIGURE) return utils::LocalizedString(u"figure"_ns); - if (mRole == roles::HEADING) return utils::LocalizedString(NS_LITERAL_STRING("heading")); + if (mRole == roles::HEADING) return utils::LocalizedString(u"heading"_ns); if (mRole == roles::MARK) { - return utils::LocalizedString(NS_LITERAL_STRING("highlight")); + return utils::LocalizedString(u"highlight"_ns); } NSString* subrole = [self moxSubrole]; diff --git a/accessible/mac/mozSelectableElements.mm b/accessible/mac/mozSelectableElements.mm index 70b32b99c06b..8201b1a4a273 100644 --- a/accessible/mac/mozSelectableElements.mm +++ b/accessible/mac/mozSelectableElements.mm @@ -91,7 +91,7 @@ - (id)moxValue { @implementation mozTabAccessible - (NSString*)moxRoleDescription { - return utils::LocalizedString(NS_LITERAL_STRING("tab")); + return utils::LocalizedString(u"tab"_ns); } - (id)moxValue { diff --git a/accessible/windows/msaa/AccessibleWrap.cpp b/accessible/windows/msaa/AccessibleWrap.cpp index 79605beb7f7e..95e7a7b27217 100644 --- a/accessible/windows/msaa/AccessibleWrap.cpp +++ b/accessible/windows/msaa/AccessibleWrap.cpp @@ -478,7 +478,7 @@ AccessibleWrap::get_accRole( if (!nodeInfo->NamespaceEquals(document->GetDefaultNamespaceID())) { nsAutoString nameSpaceURI; nodeInfo->GetNamespaceURI(nameSpaceURI); - roleString += NS_LITERAL_STRING(", ") + nameSpaceURI; + roleString += u", "_ns + nameSpaceURI; } } diff --git a/accessible/windows/msaa/ApplicationAccessibleWrap.cpp b/accessible/windows/msaa/ApplicationAccessibleWrap.cpp index 0f987b4a9052..ef84e471bbda 100644 --- a/accessible/windows/msaa/ApplicationAccessibleWrap.cpp +++ b/accessible/windows/msaa/ApplicationAccessibleWrap.cpp @@ -32,9 +32,7 @@ ApplicationAccessibleWrap::NativeAttributes() { gfxInfo->GetD2DEnabled(&isD2DEnabled); nsAutoString unused; attributes->SetStringProperty( - NS_LITERAL_CSTRING("D2D"), - isD2DEnabled ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"), - unused); + "D2D"_ns, isD2DEnabled ? u"true"_ns : u"false"_ns, unused); } return attributes.forget(); diff --git a/accessible/windows/msaa/Compatibility.cpp b/accessible/windows/msaa/Compatibility.cpp index fdd872c7ceca..918da4e7be38 100644 --- a/accessible/windows/msaa/Compatibility.cpp +++ b/accessible/windows/msaa/Compatibility.cpp @@ -282,7 +282,7 @@ static bool IsSystemOleAcc(nsCOMPtr& aFile) { return false; } - rv = oleAcc->Append(NS_LITERAL_STRING("oleacc.dll")); + rv = oleAcc->Append(u"oleacc.dll"_ns); if (NS_FAILED(rv)) { return false; } @@ -369,8 +369,7 @@ static bool UseIAccessibleProxyStub() { // IAccessible configuration in the computer's registry. Let's annotate this // so that we can easily determine this condition during crash analysis. CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IAccessibleConfig, - NS_LITERAL_CSTRING("NoSystemTypeLibOrPS")); + CrashReporter::Annotation::IAccessibleConfig, "NoSystemTypeLibOrPS"_ns); return false; } diff --git a/accessible/windows/msaa/CompatibilityUIA.cpp b/accessible/windows/msaa/CompatibilityUIA.cpp index 8576454b6cb7..9d26b1145c06 100644 --- a/accessible/windows/msaa/CompatibilityUIA.cpp +++ b/accessible/windows/msaa/CompatibilityUIA.cpp @@ -174,8 +174,7 @@ Maybe Compatibility::OnUIAMessage(WPARAM aWParam, LPARAM aLParam) { nsAutoHandle section; auto comparator = [&](const nsDependentSubstring& aName, const nsDependentSubstring& aType) -> bool { - if (aType.Equals(NS_LITERAL_STRING("Section")) && - FindInReadable(kStrHookShmem, aName) && + if (aType.Equals(u"Section"_ns) && FindInReadable(kStrHookShmem, aName) && StringEndsWith(aName, partialSectionSuffix)) { section.own(::OpenFileMapping(GENERIC_READ, FALSE, PromiseFlatString(aName).get())); @@ -274,7 +273,7 @@ Maybe Compatibility::OnUIAMessage(WPARAM aWParam, LPARAM aLParam) { // Now we check whether the object's type name matches "Section" nsDependentSubstring objTypeName( objType->TypeName.Buffer, objType->TypeName.Length / sizeof(wchar_t)); - if (!objTypeName.Equals(NS_LITERAL_STRING("Section"))) { + if (!objTypeName.Equals(u"Section"_ns)) { nonSectionObjTypes.PutEntry( static_cast(curHandle.mObjectTypeIndex)); continue; diff --git a/accessible/windows/msaa/Platform.cpp b/accessible/windows/msaa/Platform.cpp index a3a64aca4caa..0d90f6a47c6b 100644 --- a/accessible/windows/msaa/Platform.cpp +++ b/accessible/windows/msaa/Platform.cpp @@ -218,7 +218,7 @@ bool a11y::IsHandlerRegistered() { return false; } - rv = expectedHandler->Append(NS_LITERAL_STRING("AccessibleHandler.dll")); + rv = expectedHandler->Append(u"AccessibleHandler.dll"_ns); if (NS_FAILED(rv)) { return false; } @@ -337,7 +337,7 @@ void a11y::SetInstantiator(const uint32_t aPid) { if (!GetInstantiatorExecutable(aPid, getter_AddRefs(clientExe))) { #if defined(MOZ_TELEMETRY_REPORTING) || defined(MOZ_CRASHREPORTER) AccumulateInstantiatorTelemetry( - NS_LITERAL_STRING("(Failed to retrieve client image name)")); + u"(Failed to retrieve client image name)"_ns); #endif // defined(MOZ_TELEMETRY_REPORTING) || defined(MOZ_CRASHREPORTER) return; } diff --git a/accessible/windows/msaa/XULMenuAccessibleWrap.cpp b/accessible/windows/msaa/XULMenuAccessibleWrap.cpp index 0effd7473663..dc9210dbb619 100644 --- a/accessible/windows/msaa/XULMenuAccessibleWrap.cpp +++ b/accessible/windows/msaa/XULMenuAccessibleWrap.cpp @@ -29,7 +29,7 @@ ENameValueFlag XULMenuitemAccessibleWrap::Name(nsString& aName) const { mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::acceltext, accel); } - if (!accel.IsEmpty()) aName += NS_LITERAL_STRING("\t") + accel; + if (!accel.IsEmpty()) aName += u"\t"_ns + accel; return eNameOK; } diff --git a/accessible/windows/uia/uiaRawElmProvider.cpp b/accessible/windows/uia/uiaRawElmProvider.cpp index cdcf5b2788f7..a0634c446c6d 100644 --- a/accessible/windows/uia/uiaRawElmProvider.cpp +++ b/accessible/windows/uia/uiaRawElmProvider.cpp @@ -147,7 +147,7 @@ uiaRawElmProvider::GetPropertyValue(PROPERTYID aPropertyId, nsAutoString xmlRoles; nsCOMPtr attributes = mAcc->Attributes(); - attributes->GetStringProperty(NS_LITERAL_CSTRING("xml-roles"), xmlRoles); + attributes->GetStringProperty("xml-roles"_ns, xmlRoles); if (!xmlRoles.IsEmpty()) { aPropertyValue->vt = VT_BSTR; diff --git a/accessible/xul/XULTabAccessible.cpp b/accessible/xul/XULTabAccessible.cpp index 23e3c846ce28..5d30bd172608 100644 --- a/accessible/xul/XULTabAccessible.cpp +++ b/accessible/xul/XULTabAccessible.cpp @@ -87,8 +87,7 @@ Relation XULTabAccessible::RelationByType(RelationType aType) const { // Expose 'LABEL_FOR' relation on tab accessible for tabpanel accessible. ErrorResult rv; - nsIContent* parent = - mContent->AsElement()->Closest(NS_LITERAL_STRING("tabs"), rv); + nsIContent* parent = mContent->AsElement()->Closest(u"tabs"_ns, rv); if (!parent) return rel; nsCOMPtr tabsElm = diff --git a/accessible/xul/XULTreeAccessible.cpp b/accessible/xul/XULTreeAccessible.cpp index da748f68cb46..6cd9fa21818f 100644 --- a/accessible/xul/XULTreeAccessible.cpp +++ b/accessible/xul/XULTreeAccessible.cpp @@ -614,8 +614,7 @@ nsIntRect XULTreeItemAccessibleBase::BoundsInCSSPixels() const { RefPtr column = nsCoreUtils::GetFirstSensibleColumn(mTree); nsresult rv; - nsIntRect rect = - mTree->GetCoordsForCellItem(mRow, column, NS_LITERAL_STRING("cell"), rv); + nsIntRect rect = mTree->GetCoordsForCellItem(mRow, column, u"cell"_ns, rv); if (NS_FAILED(rv)) { return nsIntRect(); } @@ -843,7 +842,7 @@ void XULTreeItemAccessibleBase::DispatchClickEvent( } else { // Primary column contains a twisty we should click on. column = columns->GetPrimaryColumn(); - pseudoElm = NS_LITERAL_STRING("twisty"); + pseudoElm = u"twisty"_ns; } if (column) { diff --git a/accessible/xul/XULTreeGridAccessible.cpp b/accessible/xul/XULTreeGridAccessible.cpp index ebab95bead30..1bd87c14194b 100644 --- a/accessible/xul/XULTreeGridAccessible.cpp +++ b/accessible/xul/XULTreeGridAccessible.cpp @@ -402,8 +402,7 @@ nsIntRect XULTreeGridCellAccessible::BoundsInCSSPixels() const { // Get bounds for tree cell and add x and y of treechildren element to // x and y of the cell. nsresult rv; - nsIntRect rect = - mTree->GetCoordsForCellItem(mRow, mColumn, NS_LITERAL_STRING("cell"), rv); + nsIntRect rect = mTree->GetCoordsForCellItem(mRow, mColumn, u"cell"_ns, rv); if (NS_FAILED(rv)) { return nsIntRect(); } @@ -535,8 +534,7 @@ XULTreeGridCellAccessible::NativeAttributes() { // "cycles" attribute if (mColumn->Cycler()) - nsAccUtils::SetAccAttr(attributes, nsGkAtoms::cycles, - NS_LITERAL_STRING("true")); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::cycles, u"true"_ns); return attributes.forget(); } diff --git a/browser/components/dirprovider/DirectoryProvider.cpp b/browser/components/dirprovider/DirectoryProvider.cpp index ead1e1db6227..b16b721cd38c 100644 --- a/browser/components/dirprovider/DirectoryProvider.cpp +++ b/browser/components/dirprovider/DirectoryProvider.cpp @@ -60,12 +60,12 @@ static void AppendDistroSearchDirs(nsIProperties* aDirSvc, nsresult rv = aDirSvc->Get(XRE_APP_DISTRIBUTION_DIR, NS_GET_IID(nsIFile), getter_AddRefs(searchPlugins)); if (NS_FAILED(rv)) return; - searchPlugins->AppendNative(NS_LITERAL_CSTRING("searchplugins")); + searchPlugins->AppendNative("searchplugins"_ns); nsCOMPtr commonPlugins; rv = searchPlugins->Clone(getter_AddRefs(commonPlugins)); if (NS_SUCCEEDED(rv)) { - commonPlugins->AppendNative(NS_LITERAL_CSTRING("common")); + commonPlugins->AppendNative("common"_ns); array.AppendObject(commonPlugins); } @@ -75,7 +75,7 @@ static void AppendDistroSearchDirs(nsIProperties* aDirSvc, rv = searchPlugins->Clone(getter_AddRefs(localePlugins)); if (NS_FAILED(rv)) return; - localePlugins->AppendNative(NS_LITERAL_CSTRING("locale")); + localePlugins->AppendNative("locale"_ns); nsAutoCString defLocale; rv = prefs->GetCharPref("distribution.searchplugins.defaultLocale", diff --git a/browser/components/migration/nsIEHistoryEnumerator.cpp b/browser/components/migration/nsIEHistoryEnumerator.cpp index da5884201363..497b92bab722 100644 --- a/browser/components/migration/nsIEHistoryEnumerator.cpp +++ b/browser/components/migration/nsIEHistoryEnumerator.cpp @@ -74,11 +74,10 @@ nsIEHistoryEnumerator::HasMoreElements(bool* _retval) { mCachedNextEntry = do_CreateInstance("@mozilla.org/hash-property-bag;1"); MOZ_ASSERT(mCachedNextEntry, "Should have instanced a new property bag"); if (mCachedNextEntry) { - mCachedNextEntry->SetPropertyAsInterface(NS_LITERAL_STRING("uri"), uri); - mCachedNextEntry->SetPropertyAsAString(NS_LITERAL_STRING("title"), title); + mCachedNextEntry->SetPropertyAsInterface(u"uri"_ns, uri); + mCachedNextEntry->SetPropertyAsAString(u"title"_ns, title); if (lastVisitTimeIsValid) { - mCachedNextEntry->SetPropertyAsInt64(NS_LITERAL_STRING("time"), - lastVisited); + mCachedNextEntry->SetPropertyAsInt64(u"time"_ns, lastVisited); } *_retval = true; diff --git a/browser/components/shell/nsGNOMEShellService.cpp b/browser/components/shell/nsGNOMEShellService.cpp index b0b0f5016d9a..397e08847d27 100644 --- a/browser/components/shell/nsGNOMEShellService.cpp +++ b/browser/components/shell/nsGNOMEShellService.cpp @@ -428,19 +428,19 @@ nsGNOMEShellService::SetDesktopBackground(dom::Element* aElement, do_GetService(NS_GSETTINGSSERVICE_CONTRACTID); if (gsettings) { nsCOMPtr background_settings; - gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(kDesktopBGSchema), + gsettings->GetCollectionForSchema(nsLiteralCString(kDesktopBGSchema), getter_AddRefs(background_settings)); if (background_settings) { gchar* file_uri = g_filename_to_uri(filePath.get(), nullptr, nullptr); if (!file_uri) return NS_ERROR_FAILURE; - background_settings->SetString(NS_LITERAL_CSTRING(kDesktopOptionGSKey), + background_settings->SetString(nsLiteralCString(kDesktopOptionGSKey), options); - background_settings->SetString(NS_LITERAL_CSTRING(kDesktopImageGSKey), + background_settings->SetString(nsLiteralCString(kDesktopImageGSKey), nsDependentCString(file_uri)); g_free(file_uri); - background_settings->SetBoolean(NS_LITERAL_CSTRING(kDesktopDrawBGGSKey), + background_settings->SetBoolean(nsLiteralCString(kDesktopDrawBGGSKey), true); return rv; } @@ -460,10 +460,10 @@ nsGNOMEShellService::GetDesktopBackgroundColor(uint32_t* aColor) { nsAutoCString background; if (gsettings) { - gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(kDesktopBGSchema), + gsettings->GetCollectionForSchema(nsLiteralCString(kDesktopBGSchema), getter_AddRefs(background_settings)); if (background_settings) { - background_settings->GetString(NS_LITERAL_CSTRING(kDesktopColorGSKey), + background_settings->GetString(nsLiteralCString(kDesktopColorGSKey), background); } } @@ -506,10 +506,10 @@ nsGNOMEShellService::SetDesktopBackgroundColor(uint32_t aColor) { do_GetService(NS_GSETTINGSSERVICE_CONTRACTID); if (gsettings) { nsCOMPtr background_settings; - gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(kDesktopBGSchema), + gsettings->GetCollectionForSchema(nsLiteralCString(kDesktopBGSchema), getter_AddRefs(background_settings)); if (background_settings) { - background_settings->SetString(NS_LITERAL_CSTRING(kDesktopColorGSKey), + background_settings->SetString(nsLiteralCString(kDesktopColorGSKey), colorString); return NS_OK; } diff --git a/browser/components/shell/nsMacShellService.cpp b/browser/components/shell/nsMacShellService.cpp index 5ef6cc6ba381..8b71f807cb7f 100644 --- a/browser/components/shell/nsMacShellService.cpp +++ b/browser/components/shell/nsMacShellService.cpp @@ -27,10 +27,9 @@ using mozilla::dom::Element; using mozilla::widget::SetDesktopImage; -#define NETWORK_PREFPANE \ - NS_LITERAL_CSTRING("/System/Library/PreferencePanes/Network.prefPane") +#define NETWORK_PREFPANE "/System/Library/PreferencePanes/Network.prefPane"_ns #define DESKTOP_PREFPANE \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "/System/Library/PreferencePanes/DesktopScreenEffectsPref.prefPane") #define SAFARI_BUNDLE_IDENTIFIER "com.apple.Safari" diff --git a/browser/components/shell/nsWindowsShellService.cpp b/browser/components/shell/nsWindowsShellService.cpp index 592cf8ff2500..3b0a826f6946 100644 --- a/browser/components/shell/nsWindowsShellService.cpp +++ b/browser/components/shell/nsWindowsShellService.cpp @@ -111,10 +111,10 @@ nsresult GetHelperPath(nsAutoString& aPath) { getter_AddRefs(appHelper)); NS_ENSURE_SUCCESS(rv, rv); - rv = appHelper->SetNativeLeafName(NS_LITERAL_CSTRING("uninstall")); + rv = appHelper->SetNativeLeafName("uninstall"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = appHelper->AppendNative(NS_LITERAL_CSTRING("helper.exe")); + rv = appHelper->AppendNative("helper.exe"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = appHelper->GetPath(aPath); @@ -268,9 +268,9 @@ nsresult nsWindowsShellService::LaunchControlPanelDefaultPrograms() { return NS_ERROR_FAILURE; } - nsAutoString params(NS_LITERAL_STRING( - "control.exe /name Microsoft.DefaultPrograms " - "/page pageDefaultProgram\\pageAdvancedSettings?pszAppName=")); + nsAutoString params( + u"control.exe /name Microsoft.DefaultPrograms " + "/page pageDefaultProgram\\pageAdvancedSettings?pszAppName="_ns); nsAutoString appRegName; GetAppRegName(appRegName); params.Append(appRegName); @@ -313,16 +313,15 @@ static bool SettingsAppBelievesConnected() { return false; } - rv = regKey->Open( - nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("SOFTWARE\\Microsoft\\Windows\\Shell\\Associations"), - nsIWindowsRegKey::ACCESS_READ); + rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, + u"SOFTWARE\\Microsoft\\Windows\\Shell\\Associations"_ns, + nsIWindowsRegKey::ACCESS_READ); if (NS_FAILED(rv)) { return false; } uint32_t value; - rv = regKey->ReadIntValue(NS_LITERAL_STRING("IsConnectedAtLogon"), &value); + rv = regKey->ReadIntValue(u"IsConnectedAtLogon"_ns, &value); if (NS_FAILED(rv)) { return false; } @@ -373,12 +372,11 @@ nsresult nsWindowsShellService::InvokeHTTPOpenAsVerb() { } nsString urlStr; - nsresult rv = formatter->FormatURLPref( - NS_LITERAL_STRING("app.support.baseURL"), urlStr); + nsresult rv = formatter->FormatURLPref(u"app.support.baseURL"_ns, urlStr); if (NS_FAILED(rv)) { return rv; } - if (!StringBeginsWith(urlStr, NS_LITERAL_STRING("https://"))) { + if (!StringBeginsWith(urlStr, u"https://"_ns)) { return NS_ERROR_FAILURE; } urlStr.AppendLiteral("win10-default-browser"); @@ -615,7 +613,7 @@ nsWindowsShellService::SetDesktopBackground(dom::Element* aElement, NS_ENSURE_SUCCESS(rv, rv); rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("Control Panel\\Desktop"), + u"Control Panel\\Desktop"_ns, nsIWindowsRegKey::ACCESS_SET_VALUE); NS_ENSURE_SUCCESS(rv, rv); @@ -648,9 +646,9 @@ nsWindowsShellService::SetDesktopBackground(dom::Element* aElement, break; } - rv = regKey->WriteStringValue(NS_LITERAL_STRING("TileWallpaper"), tile); + rv = regKey->WriteStringValue(u"TileWallpaper"_ns, tile); NS_ENSURE_SUCCESS(rv, rv); - rv = regKey->WriteStringValue(NS_LITERAL_STRING("WallpaperStyle"), style); + rv = regKey->WriteStringValue(u"WallpaperStyle"_ns, style); NS_ENSURE_SUCCESS(rv, rv); rv = regKey->Close(); NS_ENSURE_SUCCESS(rv, rv); @@ -685,15 +683,14 @@ nsWindowsShellService::SetDesktopBackgroundColor(uint32_t aColor) { NS_ENSURE_SUCCESS(rv, rv); rv = regKey->Create(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("Control Panel\\Colors"), + u"Control Panel\\Colors"_ns, nsIWindowsRegKey::ACCESS_SET_VALUE); NS_ENSURE_SUCCESS(rv, rv); wchar_t rgb[12]; _snwprintf(rgb, 12, L"%u %u %u", r, g, b); - rv = regKey->WriteStringValue(NS_LITERAL_STRING("Background"), - nsDependentString(rgb)); + rv = regKey->WriteStringValue(u"Background"_ns, nsDependentString(rgb)); NS_ENSURE_SUCCESS(rv, rv); return regKey->Close(); diff --git a/caps/BasePrincipal.cpp b/caps/BasePrincipal.cpp index 28492689303f..3296b9c4f9ad 100644 --- a/caps/BasePrincipal.cpp +++ b/caps/BasePrincipal.cpp @@ -831,7 +831,7 @@ NS_IMETHODIMP BasePrincipal::GetIsOnion(bool* aIsOnion) { if (NS_FAILED(rv)) { return NS_OK; } - *aIsOnion = StringEndsWith(host, NS_LITERAL_CSTRING(".onion")); + *aIsOnion = StringEndsWith(host, ".onion"_ns); return NS_OK; } @@ -1060,13 +1060,13 @@ already_AddRefed BasePrincipal::CreateContentPrincipal( already_AddRefed BasePrincipal::CreateContentPrincipal( const nsACString& aOrigin) { - MOZ_ASSERT(!StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("[")), + MOZ_ASSERT(!StringBeginsWith(aOrigin, "["_ns), "CreateContentPrincipal does not support System and Expanded " "principals"); - MOZ_ASSERT(!StringBeginsWith(aOrigin, - NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":")), - "CreateContentPrincipal does not support NullPrincipal"); + MOZ_ASSERT( + !StringBeginsWith(aOrigin, nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":")), + "CreateContentPrincipal does not support NullPrincipal"); nsAutoCString originNoSuffix; OriginAttributes attrs; diff --git a/caps/ContentPrincipal.cpp b/caps/ContentPrincipal.cpp index 3daf333cda7b..bb7d9ce73a8d 100644 --- a/caps/ContentPrincipal.cpp +++ b/caps/ContentPrincipal.cpp @@ -147,7 +147,7 @@ nsresult ContentPrincipal::GenerateOriginNoSuffixFromURI( // sources. We check for moz-safe-about:blank since origin is an // innermost URI. !StringBeginsWith(origin->GetSpecOrDefault(), - NS_LITERAL_CSTRING("moz-safe-about:blank")))) { + "moz-safe-about:blank"_ns))) { rv = origin->GetAsciiSpec(aOriginNoSuffix); NS_ENSURE_SUCCESS(rv, rv); diff --git a/caps/NullPrincipal.cpp b/caps/NullPrincipal.cpp index 1f7af4cbab5c..0047d06decc7 100644 --- a/caps/NullPrincipal.cpp +++ b/caps/NullPrincipal.cpp @@ -237,7 +237,7 @@ nsresult NullPrincipal::PopulateJSONObject(Json::Value& aObject) { nsresult rv = mURI->GetSpec(principalURI); NS_ENSURE_SUCCESS(rv, rv); MOZ_ASSERT(principalURI.Length() == - NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":").Length() + + nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":").Length() + NSID_LENGTH - 1, "Length of the URI should be: (scheme, uuid, - nullptr)"); aObject[std::to_string(eSpec)] = principalURI.get(); diff --git a/caps/NullPrincipalURI.cpp b/caps/NullPrincipalURI.cpp index 8d886ebc1053..02176f1ea324 100644 --- a/caps/NullPrincipalURI.cpp +++ b/caps/NullPrincipalURI.cpp @@ -146,7 +146,7 @@ nsresult NullPrincipalURI::SetRef(const nsACString& aRef) { NS_IMETHODIMP NullPrincipalURI::GetPrePath(nsACString& _prePath) { - _prePath = NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":"); + _prePath = nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":"); return NS_OK; } @@ -159,7 +159,7 @@ nsresult NullPrincipalURI::SetPort(int32_t aPort) { NS_IMETHODIMP NullPrincipalURI::GetScheme(nsACString& _scheme) { - _scheme = NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME); + _scheme = nsLiteralCString(NS_NULLPRINCIPAL_SCHEME); return NS_OK; } @@ -169,7 +169,7 @@ nsresult NullPrincipalURI::SetScheme(const nsACString& aScheme) { NS_IMETHODIMP NullPrincipalURI::GetSpec(nsACString& _spec) { - _spec = NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":") + mPath; + _spec = nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":") + mPath; return NS_OK; } diff --git a/caps/OriginAttributes.cpp b/caps/OriginAttributes.cpp index 7fed2a38f759..ca2c47054b78 100644 --- a/caps/OriginAttributes.cpp +++ b/caps/OriginAttributes.cpp @@ -70,7 +70,7 @@ static void PopulateTopLevelInfoFromURI(const bool aIsTopLevelDocument, NS_ENSURE_SUCCESS_VOID(rv); if (scheme.EqualsLiteral("about")) { - MakeTopLevelInfo(scheme, NS_LITERAL_CSTRING(ABOUT_URI_FIRST_PARTY_DOMAIN), + MakeTopLevelInfo(scheme, nsLiteralCString(ABOUT_URI_FIRST_PARTY_DOMAIN), aUseSite, topLevelInfo); return; } @@ -200,27 +200,26 @@ void OriginAttributes::CreateSuffix(nsACString& aStr) const { // if (mInIsolatedMozBrowser) { - params.Set(NS_LITERAL_STRING("inBrowser"), NS_LITERAL_STRING("1")); + params.Set(u"inBrowser"_ns, u"1"_ns); } if (mUserContextId != nsIScriptSecurityManager::DEFAULT_USER_CONTEXT_ID) { value.Truncate(); value.AppendInt(mUserContextId); - params.Set(NS_LITERAL_STRING("userContextId"), value); + params.Set(u"userContextId"_ns, value); } if (mPrivateBrowsingId) { value.Truncate(); value.AppendInt(mPrivateBrowsingId); - params.Set(NS_LITERAL_STRING("privateBrowsingId"), value); + params.Set(u"privateBrowsingId"_ns, value); } if (!mFirstPartyDomain.IsEmpty()) { nsAutoString sanitizedFirstPartyDomain(mFirstPartyDomain); sanitizedFirstPartyDomain.ReplaceChar(kSourceChar, kSanitizedChar); - params.Set(NS_LITERAL_STRING("firstPartyDomain"), - sanitizedFirstPartyDomain); + params.Set(u"firstPartyDomain"_ns, sanitizedFirstPartyDomain); } if (!mGeckoViewSessionContextId.IsEmpty()) { @@ -228,15 +227,14 @@ void OriginAttributes::CreateSuffix(nsACString& aStr) const { sanitizedGeckoViewUserContextId.ReplaceChar( dom::quota::QuotaManager::kReplaceChars, kSanitizedChar); - params.Set(NS_LITERAL_STRING("geckoViewUserContextId"), - sanitizedGeckoViewUserContextId); + params.Set(u"geckoViewUserContextId"_ns, sanitizedGeckoViewUserContextId); } if (!mPartitionKey.IsEmpty()) { nsAutoString sanitizedPartitionKey(mPartitionKey); sanitizedPartitionKey.ReplaceChar(kSourceChar, kSanitizedChar); - params.Set(NS_LITERAL_STRING("partitionKey"), sanitizedPartitionKey); + params.Set(u"partitionKey"_ns, sanitizedPartitionKey); } aStr.Truncate(); diff --git a/caps/SystemPrincipal.cpp b/caps/SystemPrincipal.cpp index 075d827a0b81..ddfb5c52393a 100644 --- a/caps/SystemPrincipal.cpp +++ b/caps/SystemPrincipal.cpp @@ -26,7 +26,7 @@ NS_IMPL_CI_INTERFACE_GETTER(SystemPrincipal, nsIPrincipal, nsISerializable) already_AddRefed SystemPrincipal::Create() { RefPtr sp = new SystemPrincipal(); - sp->FinishInit(NS_LITERAL_CSTRING(SYSTEM_PRINCIPAL_SPEC), OriginAttributes()); + sp->FinishInit(nsLiteralCString(SYSTEM_PRINCIPAL_SPEC), OriginAttributes()); return sp.forget(); } diff --git a/caps/nsScriptSecurityManager.cpp b/caps/nsScriptSecurityManager.cpp index 9ce96209fec8..99742118c8ee 100644 --- a/caps/nsScriptSecurityManager.cpp +++ b/caps/nsScriptSecurityManager.cpp @@ -172,7 +172,7 @@ static nsresult GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin) { nsAutoCString scheme; rv = uri->GetScheme(scheme); NS_ENSURE_SUCCESS(rv, rv); - aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort; + aOrigin = scheme + "://"_ns + hostPort; } else { // Some URIs (e.g., nsSimpleURI) don't support host. Just // get the full spec. @@ -1029,10 +1029,9 @@ nsresult nsScriptSecurityManager::ReportError(const char* aMessageTag, // using category of "SOP" so we can link to MDN if (aInnerWindowID != 0) { - rv = error->InitWithWindowID(message, EmptyString(), EmptyString(), 0, 0, - nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("SOP"), aInnerWindowID, - true /* From chrome context */); + rv = error->InitWithWindowID( + message, EmptyString(), EmptyString(), 0, 0, nsIScriptError::errorFlag, + "SOP"_ns, aInnerWindowID, true /* From chrome context */); } else { rv = error->Init(message, EmptyString(), EmptyString(), 0, 0, nsIScriptError::errorFlag, "SOP", aFromPrivateWindow, @@ -1157,12 +1156,12 @@ nsScriptSecurityManager::CreateContentPrincipal( NS_IMETHODIMP nsScriptSecurityManager::CreateContentPrincipalFromOrigin( const nsACString& aOrigin, nsIPrincipal** aPrincipal) { - if (StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("["))) { + if (StringBeginsWith(aOrigin, "["_ns)) { return NS_ERROR_INVALID_ARG; } if (StringBeginsWith(aOrigin, - NS_LITERAL_CSTRING(NS_NULLPRINCIPAL_SCHEME ":"))) { + nsLiteralCString(NS_NULLPRINCIPAL_SCHEME ":"))) { return NS_ERROR_INVALID_ARG; } @@ -1506,8 +1505,8 @@ void nsScriptSecurityManager::AddSitesToFileURIAllowlist( // Check if the URI is schemeless. If so, add both http and https. nsAutoCString unused; if (NS_FAILED(sIOService->ExtractScheme(site, unused))) { - AddSitesToFileURIAllowlist(NS_LITERAL_CSTRING("http://") + site); - AddSitesToFileURIAllowlist(NS_LITERAL_CSTRING("https://") + site); + AddSitesToFileURIAllowlist("http://"_ns + site); + AddSitesToFileURIAllowlist("https://"_ns + site); continue; } @@ -1521,8 +1520,7 @@ void nsScriptSecurityManager::AddSitesToFileURIAllowlist( do_GetService("@mozilla.org/consoleservice;1")); if (console) { nsAutoString msg = - NS_LITERAL_STRING( - "Unable to to add site to file:// URI allowlist: ") + + u"Unable to to add site to file:// URI allowlist: "_ns + NS_ConvertASCIItoUTF16(site); console->LogStringMessage(msg.get()); } @@ -1655,8 +1653,7 @@ nsScriptSecurityManager::EnsureFileURIAllowlist() { // Figure out if this policy allows loading file:// URIs. If not, we can // skip it. nsCString checkLoadURIPrefName = - NS_LITERAL_CSTRING("capability.policy.") + policyName + - NS_LITERAL_CSTRING(".checkloaduri.enabled"); + "capability.policy."_ns + policyName + ".checkloaduri.enabled"_ns; nsAutoString value; nsresult rv = Preferences::GetString(checkLoadURIPrefName.get(), value); if (NS_FAILED(rv) || !value.LowerCaseEqualsLiteral("allaccess")) { @@ -1664,8 +1661,8 @@ nsScriptSecurityManager::EnsureFileURIAllowlist() { } // Grab the list of domains associated with this policy. - nsCString domainPrefName = NS_LITERAL_CSTRING("capability.policy.") + - policyName + NS_LITERAL_CSTRING(".sites"); + nsCString domainPrefName = + "capability.policy."_ns + policyName + ".sites"_ns; nsAutoCString siteList; Preferences::GetCString(domainPrefName.get(), siteList); AddSitesToFileURIAllowlist(siteList); diff --git a/caps/tests/gtest/TestPrincipalSerialization.cpp b/caps/tests/gtest/TestPrincipalSerialization.cpp index 8c22ea1a3adc..5184178d7217 100644 --- a/caps/tests/gtest/TestPrincipalSerialization.cpp +++ b/caps/tests/gtest/TestPrincipalSerialization.cpp @@ -73,19 +73,19 @@ TEST(PrincipalSerialization, TwoKeys) { // Sanity check that this returns a system principal nsCOMPtr systemPrincipal = - BasePrincipal::FromJSON(NS_LITERAL_CSTRING("{\"3\":{}}")); + BasePrincipal::FromJSON("{\"3\":{}}"_ns); ASSERT_EQ(BasePrincipal::Cast(systemPrincipal)->Kind(), BasePrincipal::eSystemPrincipal); // Sanity check that this returns a content principal - nsCOMPtr contentPrincipal = BasePrincipal::FromJSON( - NS_LITERAL_CSTRING("{\"1\":{\"0\":\"https://mozilla.com\"}}")); + nsCOMPtr contentPrincipal = + BasePrincipal::FromJSON("{\"1\":{\"0\":\"https://mozilla.com\"}}"_ns); ASSERT_EQ(BasePrincipal::Cast(contentPrincipal)->Kind(), BasePrincipal::eContentPrincipal); // Check both combined don't return a principal nsCOMPtr combinedPrincipal = BasePrincipal::FromJSON( - NS_LITERAL_CSTRING("{\"1\":{\"0\":\"https://mozilla.com\"},\"3\":{}}")); + "{\"1\":{\"0\":\"https://mozilla.com\"},\"3\":{}}"_ns); ASSERT_EQ(nullptr, combinedPrincipal); } diff --git a/chrome/nsChromeProtocolHandler.cpp b/chrome/nsChromeProtocolHandler.cpp index 5fc59c1bb677..76e2772d14a8 100644 --- a/chrome/nsChromeProtocolHandler.cpp +++ b/chrome/nsChromeProtocolHandler.cpp @@ -171,7 +171,7 @@ nsChromeProtocolHandler::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, nsCOMPtr url = do_QueryInterface(aURI); nsAutoCString path; rv = url->GetPathQueryRef(path); - if (StringBeginsWith(path, NS_LITERAL_CSTRING("/content/"))) { + if (StringBeginsWith(path, "/content/"_ns)) { result->SetOwner(nsContentUtils::GetSystemPrincipal()); } @@ -180,7 +180,7 @@ nsChromeProtocolHandler::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, // and with startupcache not at all), but this is where we would start // if we need to re-add. // See bug 531886, bug 533038. - result->SetContentCharset(NS_LITERAL_CSTRING("UTF-8")); + result->SetContentCharset("UTF-8"_ns); *aResult = result; NS_ADDREF(*aResult); diff --git a/chrome/nsChromeRegistryChrome.cpp b/chrome/nsChromeRegistryChrome.cpp index ac7f59ec062b..85ca64a10355 100644 --- a/chrome/nsChromeRegistryChrome.cpp +++ b/chrome/nsChromeRegistryChrome.cpp @@ -35,7 +35,7 @@ #include "nsIXULRuntime.h" #define PACKAGE_OVERRIDE_BRANCH "chrome.override_package." -#define SKIN NS_LITERAL_CSTRING("classic/1.0") +#define SKIN "classic/1.0"_ns using namespace mozilla; using mozilla::dom::ContentParent; @@ -170,8 +170,7 @@ nsresult nsChromeRegistryChrome::GetSelectedLocale(const nsACString& aPackage, nsresult nsChromeRegistryChrome::OverrideLocalePackage( const nsACString& aPackage, nsACString& aOverride) { - const nsACString& pref = - NS_LITERAL_CSTRING(PACKAGE_OVERRIDE_BRANCH) + aPackage; + const nsACString& pref = nsLiteralCString(PACKAGE_OVERRIDE_BRANCH) + aPackage; nsAutoCString override; nsresult rv = mozilla::Preferences::GetCString(PromiseFlatCString(pref).get(), override); @@ -527,8 +526,7 @@ void nsChromeRegistryChrome::ManifestLocale(ManifestProcessingContext& cx, // registered. For most cases it will be "global", but for Fennec it will be // "browser". nsAutoCString mainPackage; - nsresult rv = - OverrideLocalePackage(NS_LITERAL_CSTRING("global"), mainPackage); + nsresult rv = OverrideLocalePackage("global"_ns, mainPackage); if (NS_FAILED(rv)) { return; } @@ -592,9 +590,8 @@ void nsChromeRegistryChrome::ManifestOverride(ManifestProcessingContext& cx, nsAutoCString chromePath, resolvedPath; chromeuri->GetPathQueryRef(chromePath); resolveduri->GetPathQueryRef(resolvedPath); - chromeSkinOnly = - StringBeginsWith(chromePath, NS_LITERAL_CSTRING("/skin/")) && - StringBeginsWith(resolvedPath, NS_LITERAL_CSTRING("/skin/")); + chromeSkinOnly = StringBeginsWith(chromePath, "/skin/"_ns) && + StringBeginsWith(resolvedPath, "/skin/"_ns); } if (!chromeSkinOnly) { LogMessageWithContext( diff --git a/docshell/base/BrowsingContext.cpp b/docshell/base/BrowsingContext.cpp index 7a5eaa9e6df9..cb5e864b6182 100644 --- a/docshell/base/BrowsingContext.cpp +++ b/docshell/base/BrowsingContext.cpp @@ -1869,7 +1869,7 @@ void BrowsingContext::PostMessageMoz(JSContext* aCx, messageData = ErrorMessageData(); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Window"), + nsIScriptError::warningFlag, "DOM Window"_ns, callerInnerWindow ? callerInnerWindow->GetDocument() : nullptr, nsContentUtils::eDOM_PROPERTIES, "PostMessageSharedMemoryObjectToCrossOriginWarning"); @@ -1893,7 +1893,7 @@ void BrowsingContext::PostMessageMoz(JSContext* aCx, messageData = ErrorMessageData(); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Window"), + nsIScriptError::warningFlag, "DOM Window"_ns, callerInnerWindow ? callerInnerWindow->GetDocument() : nullptr, nsContentUtils::eDOM_PROPERTIES, "PostMessageSharedMemoryObjectToCrossOriginWarning"); @@ -2359,7 +2359,7 @@ void BrowsingContext::DidSet(FieldIndex, float aOldValue) { if (IsTop() && XRE_IsParentProcess()) { if (Element* element = GetEmbedderElement()) { auto dispatcher = MakeRefPtr( - element, NS_LITERAL_STRING("TextZoomChange"), CanBubble::eYes, + element, u"TextZoomChange"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->RunDOMEventWhenSafe(); } @@ -2389,7 +2389,7 @@ void BrowsingContext::DidSet(FieldIndex, float aOldValue) { if (IsTop() && XRE_IsParentProcess()) { if (Element* element = GetEmbedderElement()) { auto dispatcher = MakeRefPtr( - element, NS_LITERAL_STRING("FullZoomChange"), CanBubble::eYes, + element, u"FullZoomChange"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->RunDOMEventWhenSafe(); } diff --git a/docshell/base/CanonicalBrowsingContext.cpp b/docshell/base/CanonicalBrowsingContext.cpp index e6484a809e72..8e2c68243d48 100644 --- a/docshell/base/CanonicalBrowsingContext.cpp +++ b/docshell/base/CanonicalBrowsingContext.cpp @@ -349,8 +349,7 @@ void CanonicalBrowsingContext::DispatchWheelZoomChange(bool aIncrease) { return; } - auto event = aIncrease ? NS_LITERAL_STRING("DoZoomEnlargeBy10") - : NS_LITERAL_STRING("DoZoomReduceBy10"); + auto event = aIncrease ? u"DoZoomEnlargeBy10"_ns : u"DoZoomReduceBy10"_ns; auto dispatcher = MakeRefPtr( element, event, CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->PostDOMEvent(); @@ -609,10 +608,9 @@ void CanonicalBrowsingContext::PendingRemotenessChange::Finish() { // Some frontend code checks the value of the `remote` attribute on the // browser to determine if it is remote, so update the value. - browserElement->SetAttr( - kNameSpaceID_None, nsGkAtoms::remote, - mContentParent ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"), - /* notify */ true); + browserElement->SetAttr(kNameSpaceID_None, nsGkAtoms::remote, + mContentParent ? u"true"_ns : u"false"_ns, + /* notify */ true); // The process has been created, hand off to nsFrameLoaderOwner to finish // the process switch. diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp index 7ae7145a5df1..6bb1f025aeea 100644 --- a/docshell/base/nsDocShell.cpp +++ b/docshell/base/nsDocShell.cpp @@ -2339,8 +2339,7 @@ void nsDocShell::MaybeCreateInitialClientSource(nsIPrincipal* aPrincipal) { } nsCOMPtr uri; - MOZ_ALWAYS_SUCCEEDS( - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("about:blank"))); + MOZ_ALWAYS_SUCCEEDS(NS_NewURI(getter_AddRefs(uri), "about:blank"_ns)); // We're done if there is no parent controller or if this docshell // is not permitted to control for some reason. @@ -3432,7 +3431,7 @@ nsDocShell::DisplayLoadError(nsresult aError, nsIURI* aURI, RefPtr handler = mChromeEventHandler; if (handler) { nsCOMPtr element = do_QueryInterface(handler); - element->GetAttribute(NS_LITERAL_STRING("crashedPageTitle"), messageStr); + element->GetAttribute(u"crashedPageTitle"_ns, messageStr); } // DisplayLoadError requires a non-empty messageStr to proceed and call @@ -3585,7 +3584,7 @@ nsDocShell::DisplayLoadError(nsresult aError, nsIURI* aURI, } Telemetry::AccumulateCategoricalKeyed( - IsFrame() ? NS_LITERAL_CSTRING("frame") : NS_LITERAL_CSTRING("top"), + IsFrame() ? "frame"_ns : "top"_ns, mozilla::dom::LoadErrorToTelemetryLabel(aError)); // Test if the error needs to be formatted @@ -5217,8 +5216,7 @@ nsDocShell::SetupRefreshURI(nsIChannel* aChannel) { nsCOMPtr httpChannel(do_QueryInterface(aChannel, &rv)); if (NS_SUCCEEDED(rv)) { nsAutoCString refreshHeader; - rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("refresh"), - refreshHeader); + rv = httpChannel->GetResponseHeader("refresh"_ns, refreshHeader); if (!refreshHeader.IsEmpty()) { nsCOMPtr secMan = @@ -5739,7 +5737,7 @@ already_AddRefed nsDocShell::AttemptURIFixup( nsAutoCString scheme; Unused << url->GetScheme(scheme); if (Preferences::GetBool("keyword.enabled", false) && - StringBeginsWith(scheme, NS_LITERAL_CSTRING("http"))) { + StringBeginsWith(scheme, "http"_ns)) { bool attemptFixup = false; nsAutoCString host; Unused << url->GetHost(host); @@ -5855,7 +5853,7 @@ already_AddRefed nsDocShell::AttemptURIFixup( newURI = nullptr; newPostData = nullptr; Unused << NS_MutateURI(url) - .SetScheme(NS_LITERAL_CSTRING("https")) + .SetScheme("https"_ns) .Finalize(getter_AddRefs(newURI)); } } @@ -6122,7 +6120,7 @@ nsresult nsDocShell::EndPageLoad(nsIWebProgress* aProgress, if (NS_SUCCEEDED(rv) && port == -1) { nsCOMPtr httpsURI; rv = NS_MutateURI(url) - .SetScheme(NS_LITERAL_CSTRING("https")) + .SetScheme("https"_ns) .Finalize(getter_AddRefs(httpsURI)); if (NS_SUCCEEDED(rv)) { @@ -6175,9 +6173,9 @@ nsresult nsDocShell::EndPageLoad(nsIWebProgress* aProgress, params.LastElement().AssignLiteral(u"(unknown uri)"); } nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), - GetExtantDocument(), nsContentUtils::eDOM_PROPERTIES, - "UnknownProtocolNavigationPrevented", params); + nsIScriptError::warningFlag, "DOM"_ns, GetExtantDocument(), + nsContentUtils::eDOM_PROPERTIES, "UnknownProtocolNavigationPrevented", + params); } } else { // If we have a host @@ -6335,8 +6333,7 @@ nsresult nsDocShell::CreateAboutBlankContentViewer( mFiredUnloadEvent = false; nsCOMPtr docFactory = - nsContentUtils::FindInternalContentViewer( - NS_LITERAL_CSTRING("text/html")); + nsContentUtils::FindInternalContentViewer("text/html"_ns); if (docFactory) { nsCOMPtr principal, partitionedPrincipal; @@ -8892,7 +8889,7 @@ bool nsDocShell::CanLoadInParentProcess(nsIURI* aURI) { uri->GetScheme(scheme); // Allow ext+foo URIs (extension-registered custom protocols). See // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/protocol_handlers - if (StringBeginsWith(scheme, NS_LITERAL_CSTRING("ext+")) && + if (StringBeginsWith(scheme, "ext+"_ns) && !StaticPrefs::extensions_webextensions_remote()) { return true; } @@ -8981,9 +8978,9 @@ nsIPrincipal* nsDocShell::GetInheritedPrincipal( MOZ_TRY(vsh->NewSrcdocChannel(aURI, aBaseURI, aSrcdoc, aLoadInfo, getter_AddRefs(channel))); } else { - MOZ_TRY(NS_NewInputStreamChannelInternal( - getter_AddRefs(channel), aURI, aSrcdoc, NS_LITERAL_CSTRING("text/html"), - aLoadInfo, true)); + MOZ_TRY(NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aURI, + aSrcdoc, "text/html"_ns, aLoadInfo, + true)); nsCOMPtr isc = do_QueryInterface(channel); MOZ_ASSERT(isc); isc->SetBaseURI(aBaseURI); @@ -9071,9 +9068,8 @@ nsIPrincipal* nsDocShell::GetInheritedPrincipal( nsCOMPtr permissionPrincipal = BasePrincipal::CreateContentPrincipal(aLoadState->URI(), attrs); - if (nsContentUtils::IsExactSitePermAllow( - permissionPrincipal, - NS_LITERAL_CSTRING("https-only-mode-exception"))) { + if (nsContentUtils::IsExactSitePermAllow(permissionPrincipal, + "https-only-mode-exception"_ns)) { uint32_t httpsOnlyStatus = aLoadInfo->GetHttpsOnlyStatus(); httpsOnlyStatus |= nsILoadInfo::HTTPS_ONLY_EXEMPT; aLoadInfo->SetHttpsOnlyStatus(httpsOnlyStatus); @@ -9190,12 +9186,10 @@ nsIPrincipal* nsDocShell::GetInheritedPrincipal( } // save true referrer for those who need it (e.g. xpinstall whitelisting) // Currently only http and ftp channels support this. - props->SetPropertyAsInterface( - NS_LITERAL_STRING("docshell.internalReferrer"), referrer); + props->SetPropertyAsInterface(u"docshell.internalReferrer"_ns, referrer); if (aLoadState->HasLoadFlags(INTERNAL_LOAD_FLAGS_FIRST_LOAD)) { - props->SetPropertyAsBool(NS_LITERAL_STRING("docshell.newWindowTarget"), - true); + props->SetPropertyAsBool(u"docshell.newWindowTarget"_ns, true); } } @@ -11138,7 +11132,7 @@ nsDocShell::MakeEditable(bool aInWaitForUriLoad) { nsCOMPtr props(do_QueryInterface(aChannel)); if (props) { mozilla::Unused << props->GetPropertyAsBool( - NS_LITERAL_STRING("docshell.needToAddURIVisit"), &needToAddURIVisit); + u"docshell.needToAddURIVisit"_ns, &needToAddURIVisit); } return needToAddURIVisit; @@ -11151,9 +11145,9 @@ nsDocShell::MakeEditable(bool aInWaitForUriLoad) { return; } - nsresult rv = props->GetPropertyAsInterface( - NS_LITERAL_STRING("docshell.previousURI"), NS_GET_IID(nsIURI), - reinterpret_cast(aURI)); + nsresult rv = props->GetPropertyAsInterface(u"docshell.previousURI"_ns, + NS_GET_IID(nsIURI), + reinterpret_cast(aURI)); if (NS_FAILED(rv)) { // There is no last visit for this channel, so this must be the first @@ -11161,7 +11155,7 @@ nsDocShell::MakeEditable(bool aInWaitForUriLoad) { // Treat referrer as null if there is an error getting it. (void)NS_GetReferrerFromChannel(aChannel, aURI); } else { - rv = props->GetPropertyAsUint32(NS_LITERAL_STRING("docshell.previousFlags"), + rv = props->GetPropertyAsUint32(u"docshell.previousFlags"_ns, aChannelRedirectFlags); NS_WARNING_ASSERTION( @@ -11177,9 +11171,8 @@ void nsDocShell::SaveLastVisit(nsIChannel* aChannel, nsIURI* aURI, return; } - props->SetPropertyAsInterface(NS_LITERAL_STRING("docshell.previousURI"), - aURI); - props->SetPropertyAsUint32(NS_LITERAL_STRING("docshell.previousFlags"), + props->SetPropertyAsInterface(u"docshell.previousURI"_ns, aURI); + props->SetPropertyAsUint32(u"docshell.previousFlags"_ns, aChannelRedirectFlags); } @@ -11326,7 +11319,7 @@ nsresult nsDocShell::ConfirmRepost(bool* aRepost) { // locking up the browser, see bug 1412559 for an example. if (nsCOMPtr promptBag = do_QueryInterface(prompter)) { - promptBag->SetPropertyAsUint32(NS_LITERAL_STRING("modalType"), + promptBag->SetPropertyAsUint32(u"modalType"_ns, nsIPrompt::MODAL_TYPE_CONTENT); } @@ -12074,7 +12067,7 @@ nsDocShell::InitOrReusePrintPreviewViewer(nsIWebBrowserPrint** aPrintPreview) { nsCOMPtr principal = NullPrincipal::CreateWithInheritedAttributes(this); nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("about:printpreview")); + NS_NewURI(getter_AddRefs(uri), "about:printpreview"_ns); // Reuse the null principal for the partitioned principal. // XXXehsan is that the right principal to use here? nsresult rv = CreateAboutBlankContentViewer(principal, principal, diff --git a/docshell/base/nsDocShellTreeOwner.cpp b/docshell/base/nsDocShellTreeOwner.cpp index 02cf6537f484..7881972a1c02 100644 --- a/docshell/base/nsDocShellTreeOwner.cpp +++ b/docshell/base/nsDocShellTreeOwner.cpp @@ -811,9 +811,9 @@ nsDocShellTreeOwner::AddChromeListeners() { EventListenerManager* elmP = target->GetOrCreateListenerManager(); if (elmP) { - elmP->AddEventListenerByType(this, NS_LITERAL_STRING("dragover"), + elmP->AddEventListenerByType(this, u"dragover"_ns, TrustedEventsAtSystemGroupBubble()); - elmP->AddEventListenerByType(this, NS_LITERAL_STRING("drop"), + elmP->AddEventListenerByType(this, u"drop"_ns, TrustedEventsAtSystemGroupBubble()); } @@ -835,9 +835,9 @@ nsDocShellTreeOwner::RemoveChromeListeners() { EventListenerManager* elmP = piTarget->GetOrCreateListenerManager(); if (elmP) { - elmP->RemoveEventListenerByType(this, NS_LITERAL_STRING("dragover"), + elmP->RemoveEventListenerByType(this, u"dragover"_ns, TrustedEventsAtSystemGroupBubble()); - elmP->RemoveEventListenerByType(this, NS_LITERAL_STRING("drop"), + elmP->RemoveEventListenerByType(this, u"drop"_ns, TrustedEventsAtSystemGroupBubble()); } @@ -1009,18 +1009,18 @@ ChromeTooltipListener::AddTooltipListener() { if (mEventTarget) { nsresult rv = NS_OK; #ifndef XP_WIN - rv = mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("keydown"), - this, false, false); + rv = + mEventTarget->AddSystemEventListener(u"keydown"_ns, this, false, false); NS_ENSURE_SUCCESS(rv, rv); #endif - rv = mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("mousedown"), - this, false, false); + rv = mEventTarget->AddSystemEventListener(u"mousedown"_ns, this, false, + false); NS_ENSURE_SUCCESS(rv, rv); - rv = mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("mouseout"), - this, false, false); + rv = mEventTarget->AddSystemEventListener(u"mouseout"_ns, this, false, + false); NS_ENSURE_SUCCESS(rv, rv); - rv = mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("mousemove"), - this, false, false); + rv = mEventTarget->AddSystemEventListener(u"mousemove"_ns, this, false, + false); NS_ENSURE_SUCCESS(rv, rv); mTooltipListenerInstalled = true; @@ -1049,15 +1049,11 @@ NS_IMETHODIMP ChromeTooltipListener::RemoveTooltipListener() { if (mEventTarget) { #ifndef XP_WIN - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), this, - false); + mEventTarget->RemoveSystemEventListener(u"keydown"_ns, this, false); #endif - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"), - this, false); - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("mouseout"), this, - false); - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("mousemove"), - this, false); + mEventTarget->RemoveSystemEventListener(u"mousedown"_ns, this, false); + mEventTarget->RemoveSystemEventListener(u"mouseout"_ns, this, false); + mEventTarget->RemoveSystemEventListener(u"mousemove"_ns, this, false); mTooltipListenerInstalled = false; } diff --git a/docshell/base/nsPingListener.cpp b/docshell/base/nsPingListener.cpp index a6a732a10346..85c01626f484 100644 --- a/docshell/base/nsPingListener.cpp +++ b/docshell/base/nsPingListener.cpp @@ -126,25 +126,21 @@ static void SendPing(void* aClosure, nsIContent* aContent, nsIURI* aURI, MOZ_ASSERT(NS_SUCCEEDED(rv)); } - rv = httpChan->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChan->SetRequestMethod("POST"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Remove extraneous request headers (to reduce request size) - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("accept"), EmptyCString(), - false); + rv = httpChan->SetRequestHeader("accept"_ns, EmptyCString(), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("accept-language"), - EmptyCString(), false); + rv = httpChan->SetRequestHeader("accept-language"_ns, EmptyCString(), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("accept-encoding"), - EmptyCString(), false); + rv = httpChan->SetRequestHeader("accept-encoding"_ns, EmptyCString(), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Always send a Ping-To header. nsAutoCString pingTo; if (NS_SUCCEEDED(info->target->GetSpec(pingTo))) { - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Ping-To"), pingTo, - false); + rv = httpChan->SetRequestHeader("Ping-To"_ns, pingTo, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -178,8 +174,7 @@ static void SendPing(void* aClosure, nsIContent* aContent, nsIURI* aURI, if (sameOrigin || !referrerIsSecure) { nsAutoCString pingFrom; if (NS_SUCCEEDED(referrer->GetSpec(pingFrom))) { - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Ping-From"), - pingFrom, false); + rv = httpChan->SetRequestHeader("Ping-From"_ns, pingFrom, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -206,9 +201,8 @@ static void SendPing(void* aClosure, nsIContent* aContent, nsIURI* aURI, return; } - uploadChan->ExplicitSetUploadStream( - uploadStream, NS_LITERAL_CSTRING("text/ping"), uploadData.Length(), - NS_LITERAL_CSTRING("POST"), false); + uploadChan->ExplicitSetUploadStream(uploadStream, "text/ping"_ns, + uploadData.Length(), "POST"_ns, false); // The channel needs to have a loadgroup associated with it, so that we can // cancel the channel and any redirected channels it may create. diff --git a/docshell/shistory/nsSHistory.cpp b/docshell/shistory/nsSHistory.cpp index 61f6f5c89be8..1e0663467dcb 100644 --- a/docshell/shistory/nsSHistory.cpp +++ b/docshell/shistory/nsSHistory.cpp @@ -78,16 +78,16 @@ extern mozilla::LazyLogModule gPageCacheLog; // nsIURI *uri = [...]; // LOG_SPEC(("The URI is %s.", _spec), uri); // -#define LOG_SPEC(format, uri) \ - PR_BEGIN_MACRO \ - if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \ - nsAutoCString _specStr(NS_LITERAL_CSTRING("(null)")); \ - if (uri) { \ - _specStr = uri->GetSpecOrDefault(); \ - } \ - const char* _spec = _specStr.get(); \ - LOG(format); \ - } \ +#define LOG_SPEC(format, uri) \ + PR_BEGIN_MACRO \ + if (MOZ_LOG_TEST(gSHistoryLog, LogLevel::Debug)) { \ + nsAutoCString _specStr("(null)"_ns); \ + if (uri) { \ + _specStr = uri->GetSpecOrDefault(); \ + } \ + const char* _spec = _specStr.get(); \ + LOG(format); \ + } \ PR_END_MACRO // This macro makes it easy to log a message including an SHEntry's URI. diff --git a/dom/abort/AbortSignal.cpp b/dom/abort/AbortSignal.cpp index 231b8ea00f89..3da1f213e7bf 100644 --- a/dom/abort/AbortSignal.cpp +++ b/dom/abort/AbortSignal.cpp @@ -80,8 +80,7 @@ void AbortSignal::Abort() { init.mBubbles = false; init.mCancelable = false; - RefPtr event = - Event::Constructor(this, NS_LITERAL_STRING("abort"), init); + RefPtr event = Event::Constructor(this, u"abort"_ns, init); event->SetTrusted(true); DispatchEvent(*event); diff --git a/dom/animation/Animation.cpp b/dom/animation/Animation.cpp index 440ea724ac84..e7c52db5a7a6 100644 --- a/dom/animation/Animation.cpp +++ b/dom/animation/Animation.cpp @@ -541,8 +541,7 @@ void Animation::Cancel(PostRestyleMode aPostRestyle) { } ResetFinishedPromise(); - QueuePlaybackEvent(NS_LITERAL_STRING("cancel"), - GetTimelineCurrentTimeAsTimeStamp()); + QueuePlaybackEvent(u"cancel"_ns, GetTimelineCurrentTimeAsTimeStamp()); } StickyTimeDuration activeTime = @@ -1153,8 +1152,7 @@ void Animation::Remove() { UpdateEffect(PostRestyleMode::IfNeeded); PostUpdate(); - QueuePlaybackEvent(NS_LITERAL_STRING("remove"), - GetTimelineCurrentTimeAsTimeStamp()); + QueuePlaybackEvent(u"remove"_ns, GetTimelineCurrentTimeAsTimeStamp()); } bool Animation::HasLowerCompositeOrderThan(const Animation& aOther) const { @@ -1809,8 +1807,7 @@ void Animation::DoFinishNotificationImmediately(MicroTaskRunnable* aAsync) { MaybeResolveFinishedPromise(); - QueuePlaybackEvent(NS_LITERAL_STRING("finish"), - AnimationTimeToTimeStamp(EffectEnd())); + QueuePlaybackEvent(u"finish"_ns, AnimationTimeToTimeStamp(EffectEnd())); } void Animation::QueuePlaybackEvent(const nsAString& aName, diff --git a/dom/animation/KeyframeEffect.cpp b/dom/animation/KeyframeEffect.cpp index 80c812bfe98f..3a9deb3133b2 100644 --- a/dom/animation/KeyframeEffect.cpp +++ b/dom/animation/KeyframeEffect.cpp @@ -1106,7 +1106,7 @@ static void CreatePropertyValue( aResult.mEasing.Construct(); aTimingFunction->AppendToString(aResult.mEasing.Value()); } else { - aResult.mEasing.Construct(NS_LITERAL_STRING("linear")); + aResult.mEasing.Construct(u"linear"_ns); } aResult.mComposite = aComposite; diff --git a/dom/animation/KeyframeUtils.cpp b/dom/animation/KeyframeUtils.cpp index 5ad53ddbdcd4..0cbc00cb03fd 100644 --- a/dom/animation/KeyframeUtils.cpp +++ b/dom/animation/KeyframeUtils.cpp @@ -625,9 +625,9 @@ static void ReportInvalidPropertyValueToConsole( params.AppendElement(aInvalidPropertyValue); CopyASCIItoUTF16(nsCSSProps::GetStringValue(aProperty), *params.AppendElement()); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Animation"), aDoc, - nsContentUtils::eDOM_PROPERTIES, "InvalidKeyframePropertyValue", params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Animation"_ns, + aDoc, nsContentUtils::eDOM_PROPERTIES, + "InvalidKeyframePropertyValue", params); } /** diff --git a/dom/base/AnonymousContent.cpp b/dom/base/AnonymousContent.cpp index d206b61423f3..71ab27968d4e 100644 --- a/dom/base/AnonymousContent.cpp +++ b/dom/base/AnonymousContent.cpp @@ -191,9 +191,8 @@ void AnonymousContent::GetComputedStylePropertyValue( return; } - RefPtr cs = - new nsComputedDOMStyle(element, NS_LITERAL_STRING(""), - element->OwnerDoc(), nsComputedDOMStyle::eAll); + RefPtr cs = new nsComputedDOMStyle( + element, u""_ns, element->OwnerDoc(), nsComputedDOMStyle::eAll); aRv = cs->GetPropertyValue(aPropertyName, aResult); } diff --git a/dom/base/BodyUtil.cpp b/dom/base/BodyUtil.cpp index c59c4309b09b..ec8c9519b888 100644 --- a/dom/base/BodyUtil.cpp +++ b/dom/base/BodyUtil.cpp @@ -155,15 +155,13 @@ class MOZ_STACK_CLASS FormDataParser { continue; } - if (seenFormData && - StringBeginsWith(token, NS_LITERAL_CSTRING("name="))) { + if (seenFormData && StringBeginsWith(token, "name="_ns)) { mName = StringTail(token, token.Length() - 5); mName.Trim(" \""); continue; } - if (seenFormData && - StringBeginsWith(token, NS_LITERAL_CSTRING("filename="))) { + if (seenFormData && StringBeginsWith(token, "filename="_ns)) { mFilename = StringTail(token, token.Length() - 9); mFilename.Trim(" \""); continue; @@ -323,7 +321,7 @@ class MOZ_STACK_CLASS FormDataParser { case START_PART: mName.SetIsVoid(true); mFilename.SetIsVoid(true); - mContentType = NS_LITERAL_CSTRING("text/plain"); + mContentType = "text/plain"_ns; // MUST start with boundary. if (!PushOverBoundary(boundaryString, start, end)) { diff --git a/dom/base/ChromeUtils.cpp b/dom/base/ChromeUtils.cpp index 0c9542782e8c..ad1062ed0a0a 100644 --- a/dom/base/ChromeUtils.cpp +++ b/dom/base/ChromeUtils.cpp @@ -178,7 +178,7 @@ void ChromeUtils::ReleaseAssert(GlobalObject& aGlobal, bool aCondition, location->GetFilename(aGlobal.Context(), filename); lineNo = location->GetLineNumber(aGlobal.Context()); } else { - filename.Assign(NS_LITERAL_STRING("")); + filename.Assign(u""_ns); } // Convert to utf-8 for adding as the MozCrashReason. @@ -794,8 +794,7 @@ already_AddRefed ChromeUtils::RequestProcInfo(GlobalObject& aGlobal, global->EventTargetFor(TaskCategory::Performance); // Getting the parent proc info - mozilla::GetProcInfo(parentPid, 0, mozilla::ProcType::Browser, - NS_LITERAL_STRING("")) + mozilla::GetProcInfo(parentPid, 0, mozilla::ProcType::Browser, u""_ns) ->Then( target, __func__, [target, domPromise, parentPid](ProcInfo aParentInfo) { diff --git a/dom/base/CustomElementRegistry.cpp b/dom/base/CustomElementRegistry.cpp index 02c18e339f18..71794b3d3730 100644 --- a/dom/base/CustomElementRegistry.cpp +++ b/dom/base/CustomElementRegistry.cpp @@ -905,8 +905,7 @@ void CustomElementRegistry::Define( * any exceptions from the conversion. */ if (callbacksHolder->mAttributeChangedCallback.WasPassed()) { - if (!JSObjectToAtomArray(aCx, constructor, - NS_LITERAL_STRING("observedAttributes"), + if (!JSObjectToAtomArray(aCx, constructor, u"observedAttributes"_ns, observedAttributes, aRv)) { return; } @@ -922,8 +921,7 @@ void CustomElementRegistry::Define( * Rethrow any exceptions from the conversion. */ if (StaticPrefs::dom_webcomponents_elementInternals_enabled()) { - if (!JSObjectToAtomArray(aCx, constructor, - NS_LITERAL_STRING("disabledFeatures"), + if (!JSObjectToAtomArray(aCx, constructor, u"disabledFeatures"_ns, disabledFeatures, aRv)) { return; } @@ -994,7 +992,7 @@ void CustomElementRegistry::Define( JS::Rooted detail(aCx, JS::StringValue(nameJsStr)); RefPtr event = NS_NewDOMCustomEvent(doc, nullptr, nullptr); - event->InitCustomEvent(aCx, NS_LITERAL_STRING("customelementdefined"), + event->InitCustomEvent(aCx, u"customelementdefined"_ns, /* CanBubble */ true, /* Cancelable */ true, detail); event->SetTrusted(true); diff --git a/dom/base/DOMException.cpp b/dom/base/DOMException.cpp index 449a5838df71..5f5cf6a4b5ae 100644 --- a/dom/base/DOMException.cpp +++ b/dom/base/DOMException.cpp @@ -362,7 +362,7 @@ already_AddRefed DOMException::Constructor( const Optional& aName) { nsresult exceptionResult = NS_OK; uint16_t exceptionCode = 0; - nsCString name(NS_LITERAL_CSTRING("Error")); + nsCString name("Error"_ns); if (aName.WasPassed()) { CopyUTF16toUTF8(aName.Value(), name); diff --git a/dom/base/DOMImplementation.cpp b/dom/base/DOMImplementation.cpp index 4c2a8174a730..aafac6c08208 100644 --- a/dom/base/DOMImplementation.cpp +++ b/dom/base/DOMImplementation.cpp @@ -96,11 +96,11 @@ nsresult DOMImplementation::CreateDocument(const nsAString& aNamespaceURI, // document to the new instance. if (aNamespaceURI.EqualsLiteral("http://www.w3.org/1999/xhtml")) { - doc->SetContentType(NS_LITERAL_STRING("application/xhtml+xml")); + doc->SetContentType(u"application/xhtml+xml"_ns); } else if (aNamespaceURI.EqualsLiteral("http://www.w3.org/2000/svg")) { - doc->SetContentType(NS_LITERAL_STRING("image/svg+xml")); + doc->SetContentType(u"image/svg+xml"_ns); } else { - doc->SetContentType(NS_LITERAL_STRING("application/xml")); + doc->SetContentType(u"application/xml"_ns); } doc->SetReadyStateInternal(Document::READYSTATE_COMPLETE); @@ -145,18 +145,18 @@ nsresult DOMImplementation::CreateHTMLDocument(const nsAString& aTitle, NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr root = - doc->CreateElem(NS_LITERAL_STRING("html"), nullptr, kNameSpaceID_XHTML); + doc->CreateElem(u"html"_ns, nullptr, kNameSpaceID_XHTML); rv = doc->AppendChildTo(root, false); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr head = - doc->CreateElem(NS_LITERAL_STRING("head"), nullptr, kNameSpaceID_XHTML); + doc->CreateElem(u"head"_ns, nullptr, kNameSpaceID_XHTML); rv = root->AppendChildTo(head, false); NS_ENSURE_SUCCESS(rv, rv); if (!DOMStringIsNull(aTitle)) { - nsCOMPtr title = doc->CreateElem(NS_LITERAL_STRING("title"), - nullptr, kNameSpaceID_XHTML); + nsCOMPtr title = + doc->CreateElem(u"title"_ns, nullptr, kNameSpaceID_XHTML); rv = head->AppendChildTo(title, false); NS_ENSURE_SUCCESS(rv, rv); @@ -169,7 +169,7 @@ nsresult DOMImplementation::CreateHTMLDocument(const nsAString& aTitle, } nsCOMPtr body = - doc->CreateElem(NS_LITERAL_STRING("body"), nullptr, kNameSpaceID_XHTML); + doc->CreateElem(u"body"_ns, nullptr, kNameSpaceID_XHTML); rv = root->AppendChildTo(body, false); NS_ENSURE_SUCCESS(rv, rv); diff --git a/dom/base/DOMParser.cpp b/dom/base/DOMParser.cpp index e408e35e0ba7..d897aeb46018 100644 --- a/dom/base/DOMParser.cpp +++ b/dom/base/DOMParser.cpp @@ -96,8 +96,7 @@ already_AddRefed DOMParser::ParseFromString(const nsAString& aStr, return nullptr; } - return ParseFromStream(stream, NS_LITERAL_STRING("UTF-8"), utf8str.Length(), - aType, aRv); + return ParseFromStream(stream, u"UTF-8"_ns, utf8str.Length(), aType, aRv); } already_AddRefed DOMParser::ParseFromSafeString(const nsAString& aStr, diff --git a/dom/base/DOMRequest.cpp b/dom/base/DOMRequest.cpp index 6226cb5cbb6a..aae5cbce83f4 100644 --- a/dom/base/DOMRequest.cpp +++ b/dom/base/DOMRequest.cpp @@ -82,7 +82,7 @@ void DOMRequest::FireSuccess(JS::Handle aResult) { } mResult = aResult; - FireEvent(NS_LITERAL_STRING("success"), false, false); + FireEvent(u"success"_ns, false, false); if (mPromise) { mPromise->MaybeResolve(mResult); @@ -99,7 +99,7 @@ void DOMRequest::FireError(const nsAString& aError) { mError = DOMException::Create(NS_ERROR_DOM_UNKNOWN_ERR, NS_ConvertUTF16toUTF8(aError)); - FireEvent(NS_LITERAL_STRING("error"), true, true); + FireEvent(u"error"_ns, true, true); if (mPromise) { mPromise->MaybeRejectBrokenly(mError); @@ -114,7 +114,7 @@ void DOMRequest::FireError(nsresult aError) { mDone = true; mError = DOMException::Create(aError); - FireEvent(NS_LITERAL_STRING("error"), true, true); + FireEvent(u"error"_ns, true, true); if (mPromise) { mPromise->MaybeRejectBrokenly(mError); @@ -129,7 +129,7 @@ void DOMRequest::FireDetailedError(DOMException& aError) { mDone = true; mError = &aError; - FireEvent(NS_LITERAL_STRING("error"), true, true); + FireEvent(u"error"_ns, true, true); if (mPromise) { mPromise->MaybeRejectBrokenly(mError); diff --git a/dom/base/DocGroup.cpp b/dom/base/DocGroup.cpp index 36f1861efe86..c063714e1dde 100644 --- a/dom/base/DocGroup.cpp +++ b/dom/base/DocGroup.cpp @@ -178,8 +178,7 @@ DocGroup::DocGroup(BrowsingContextGroup* aBrowsingContextGroup, mArena = new mozilla::dom::DOMArena(); } - mPerformanceCounter = - new mozilla::PerformanceCounter(NS_LITERAL_CSTRING("DocGroup:") + aKey); + mPerformanceCounter = new mozilla::PerformanceCounter("DocGroup:"_ns + aKey); } DocGroup::~DocGroup() { diff --git a/dom/base/Document.cpp b/dom/base/Document.cpp index 7866bb942a80..686262b43e64 100644 --- a/dom/base/Document.cpp +++ b/dom/base/Document.cpp @@ -2452,8 +2452,8 @@ void Document::Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup) { nsCOMPtr bag = do_QueryInterface(aChannel); if (bag) { nsCOMPtr baseURI; - bag->GetPropertyAsInterface(NS_LITERAL_STRING("baseURI"), - NS_GET_IID(nsIURI), getter_AddRefs(baseURI)); + bag->GetPropertyAsInterface(u"baseURI"_ns, NS_GET_IID(nsIURI), + getter_AddRefs(baseURI)); if (baseURI) { mDocumentBaseURI = baseURI; mChromeXHRDocBaseURI = nullptr; @@ -2959,7 +2959,7 @@ static void WarnIfSandboxIneffective(nsIDocShell* aDocShell, !(aSandboxFlags & SANDBOXED_TOPLEVEL_NAVIGATION_USER_ACTIVATION)) { nsCOMPtr iframeUri; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Iframe Sandbox"), + nsIScriptError::warningFlag, "Iframe Sandbox"_ns, aDocShell->GetDocument(), nsContentUtils::eSECURITY_PROPERTIES, "BothAllowTopNavigationAndUserActivationPresent"); } @@ -3002,11 +3002,11 @@ static void WarnIfSandboxIneffective(nsIDocShell* aDocShell, nsCOMPtr parentDocument = parentDocShell->GetDocument(); nsCOMPtr iframeUri; parentChannel->GetURI(getter_AddRefs(iframeUri)); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Iframe Sandbox"), - parentDocument, nsContentUtils::eSECURITY_PROPERTIES, - "BothAllowScriptsAndSameOriginPresent", nsTArray(), - iframeUri); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, + "Iframe Sandbox"_ns, parentDocument, + nsContentUtils::eSECURITY_PROPERTIES, + "BothAllowScriptsAndSameOriginPresent", + nsTArray(), iframeUri); } } @@ -3066,8 +3066,8 @@ nsresult Document::StartDocumentLoad(const char* aCommand, nsIChannel* aChannel, nsAutoCString contentType; nsCOMPtr bag = do_QueryInterface(aChannel); - if ((bag && NS_SUCCEEDED(bag->GetPropertyAsACString( - NS_LITERAL_STRING("contentType"), contentType))) || + if ((bag && NS_SUCCEEDED(bag->GetPropertyAsACString(u"contentType"_ns, + contentType))) || NS_SUCCEEDED(aChannel->GetContentType(contentType))) { // XXX this is only necessary for viewsource: nsACString::const_iterator start, end, semicolon; @@ -3350,12 +3350,11 @@ nsresult Document::InitCSP(nsIChannel* aChannel) { } if (httpChannel) { - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy"), tCspHeaderValue); + Unused << httpChannel->GetResponseHeader("content-security-policy"_ns, + tCspHeaderValue); Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy-report-only"), - tCspROHeaderValue); + "content-security-policy-report-only"_ns, tCspROHeaderValue); } NS_ConvertASCIItoUTF16 cspHeaderValue(tCspHeaderValue); NS_ConvertASCIItoUTF16 cspROHeaderValue(tCspROHeaderValue); @@ -3506,8 +3505,7 @@ nsresult Document::InitFeaturePolicy(nsIChannel* aChannel) { // query the policy from the header nsAutoCString value; - rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Feature-Policy"), - value); + rv = httpChannel->GetResponseHeader("Feature-Policy"_ns, value); if (NS_SUCCEEDED(rv)) { mFeaturePolicy->SetDeclaredPolicy(this, NS_ConvertUTF8toUTF16(value), NodePrincipal(), nullptr); @@ -4165,349 +4163,349 @@ void Document::EnsureInitializeInternalCommandDataHashtable() { sInternalCommandDataHashtable = new InternalCommandDataHashtable(); // clang-format off sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("bold"), + u"bold"_ns, InternalCommandData( "cmd_bold", Command::FormatBold, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("italic"), + u"italic"_ns, InternalCommandData( "cmd_italic", Command::FormatItalic, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("underline"), + u"underline"_ns, InternalCommandData( "cmd_underline", Command::FormatUnderline, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("strikethrough"), + u"strikethrough"_ns, InternalCommandData( "cmd_strikethrough", Command::FormatStrikeThrough, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("subscript"), + u"subscript"_ns, InternalCommandData( "cmd_subscript", Command::FormatSubscript, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("superscript"), + u"superscript"_ns, InternalCommandData( "cmd_superscript", Command::FormatSuperscript, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("cut"), + u"cut"_ns, InternalCommandData( "cmd_cut", Command::Cut, ExecCommandParam::Ignore, CutCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("copy"), + u"copy"_ns, InternalCommandData( "cmd_copy", Command::Copy, ExecCommandParam::Ignore, CopyCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("paste"), + u"paste"_ns, InternalCommandData( "cmd_paste", Command::Paste, ExecCommandParam::Ignore, PasteCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("delete"), + u"delete"_ns, InternalCommandData( "cmd_deleteCharBackward", Command::DeleteCharBackward, ExecCommandParam::Ignore, DeleteCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("forwarddelete"), + u"forwarddelete"_ns, InternalCommandData( "cmd_deleteCharForward", Command::DeleteCharForward, ExecCommandParam::Ignore, DeleteCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("selectall"), + u"selectall"_ns, InternalCommandData( "cmd_selectAll", Command::SelectAll, ExecCommandParam::Ignore, SelectAllCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("undo"), + u"undo"_ns, InternalCommandData( "cmd_undo", Command::HistoryUndo, ExecCommandParam::Ignore, UndoCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("redo"), + u"redo"_ns, InternalCommandData( "cmd_redo", Command::HistoryRedo, ExecCommandParam::Ignore, RedoCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("indent"), + u"indent"_ns, InternalCommandData("cmd_indent", Command::FormatIndent, ExecCommandParam::Ignore, IndentCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("outdent"), + u"outdent"_ns, InternalCommandData( "cmd_outdent", Command::FormatOutdent, ExecCommandParam::Ignore, OutdentCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("backcolor"), + u"backcolor"_ns, InternalCommandData( "cmd_highlight", Command::FormatBackColor, ExecCommandParam::String, HighlightColorStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("hilitecolor"), + u"hilitecolor"_ns, InternalCommandData( "cmd_highlight", Command::FormatBackColor, ExecCommandParam::String, HighlightColorStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("forecolor"), + u"forecolor"_ns, InternalCommandData( "cmd_fontColor", Command::FormatFontColor, ExecCommandParam::String, FontColorStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("fontname"), + u"fontname"_ns, InternalCommandData( "cmd_fontFace", Command::FormatFontName, ExecCommandParam::String, FontFaceStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("fontsize"), + u"fontsize"_ns, InternalCommandData( "cmd_fontSize", Command::FormatFontSize, ExecCommandParam::String, FontSizeStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("increasefontsize"), + u"increasefontsize"_ns, InternalCommandData( "cmd_increaseFont", Command::FormatIncreaseFontSize, ExecCommandParam::Ignore, IncreaseFontSizeCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("decreasefontsize"), + u"decreasefontsize"_ns, InternalCommandData( "cmd_decreaseFont", Command::FormatDecreaseFontSize, ExecCommandParam::Ignore, DecreaseFontSizeCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("inserthorizontalrule"), + u"inserthorizontalrule"_ns, InternalCommandData( "cmd_insertHR", Command::InsertHorizontalRule, ExecCommandParam::Ignore, InsertTagCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("createlink"), + u"createlink"_ns, InternalCommandData( "cmd_insertLinkNoUI", Command::InsertLink, ExecCommandParam::String, InsertTagCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertimage"), + u"insertimage"_ns, InternalCommandData( "cmd_insertImageNoUI", Command::InsertImage, ExecCommandParam::String, InsertTagCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("inserthtml"), + u"inserthtml"_ns, InternalCommandData( "cmd_insertHTML", Command::InsertHTML, ExecCommandParam::String, InsertHTMLCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("inserttext"), + u"inserttext"_ns, InternalCommandData( "cmd_insertText", Command::InsertText, ExecCommandParam::String, InsertPlaintextCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("gethtml"), + u"gethtml"_ns, InternalCommandData( "cmd_getContents", Command::GetHTML, ExecCommandParam::Ignore, nullptr)); // Not defined in EditorCommands.h sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("justifyleft"), + u"justifyleft"_ns, InternalCommandData( "cmd_align", Command::FormatJustifyLeft, ExecCommandParam::Ignore, // Will be set to "left" AlignCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("justifyright"), + u"justifyright"_ns, InternalCommandData( "cmd_align", Command::FormatJustifyRight, ExecCommandParam::Ignore, // Will be set to "right" AlignCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("justifycenter"), + u"justifycenter"_ns, InternalCommandData( "cmd_align", Command::FormatJustifyCenter, ExecCommandParam::Ignore, // Will be set to "center" AlignCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("justifyfull"), + u"justifyfull"_ns, InternalCommandData( "cmd_align", Command::FormatJustifyFull, ExecCommandParam::Ignore, // Will be set to "justify" AlignCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("removeformat"), + u"removeformat"_ns, InternalCommandData( "cmd_removeStyles", Command::FormatRemove, ExecCommandParam::Ignore, RemoveStylesCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("unlink"), + u"unlink"_ns, InternalCommandData( "cmd_removeLinks", Command::FormatRemoveLink, ExecCommandParam::Ignore, StyleUpdatingCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertorderedlist"), + u"insertorderedlist"_ns, InternalCommandData( "cmd_ol", Command::InsertOrderedList, ExecCommandParam::Ignore, ListCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertunorderedlist"), + u"insertunorderedlist"_ns, InternalCommandData( "cmd_ul", Command::InsertUnorderedList, ExecCommandParam::Ignore, ListCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertparagraph"), + u"insertparagraph"_ns, InternalCommandData( "cmd_insertParagraph", Command::InsertParagraph, ExecCommandParam::Ignore, InsertParagraphCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertlinebreak"), + u"insertlinebreak"_ns, InternalCommandData( "cmd_insertLineBreak", Command::InsertLineBreak, ExecCommandParam::Ignore, InsertLineBreakCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("formatblock"), + u"formatblock"_ns, InternalCommandData( "cmd_paragraphState", Command::FormatBlock, ExecCommandParam::String, ParagraphStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("heading"), + u"heading"_ns, InternalCommandData( "cmd_paragraphState", Command::FormatBlock, ExecCommandParam::String, ParagraphStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("styleWithCSS"), + u"styleWithCSS"_ns, InternalCommandData( "cmd_setDocumentUseCSS", Command::SetDocumentUseCSS, ExecCommandParam::Boolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("usecss"), // Legacy command + u"usecss"_ns, // Legacy command InternalCommandData( "cmd_setDocumentUseCSS", Command::SetDocumentUseCSS, ExecCommandParam::InvertedBoolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("contentReadOnly"), + u"contentReadOnly"_ns, InternalCommandData( "cmd_setDocumentReadOnly", Command::SetDocumentReadOnly, ExecCommandParam::Boolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("readonly"), // Legacy command + u"readonly"_ns, // Legacy command InternalCommandData( "cmd_setDocumentReadOnly", Command::SetDocumentReadOnly, ExecCommandParam::InvertedBoolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("insertBrOnReturn"), + u"insertBrOnReturn"_ns, InternalCommandData( "cmd_insertBrOnReturn", Command::SetDocumentInsertBROnEnterKeyPress, ExecCommandParam::Boolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("defaultParagraphSeparator"), + u"defaultParagraphSeparator"_ns, InternalCommandData( "cmd_defaultParagraphSeparator", Command::SetDocumentDefaultParagraphSeparator, ExecCommandParam::String, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("enableObjectResizing"), + u"enableObjectResizing"_ns, InternalCommandData( "cmd_enableObjectResizing", Command::ToggleObjectResizers, ExecCommandParam::Boolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("enableInlineTableEditing"), + u"enableInlineTableEditing"_ns, InternalCommandData( "cmd_enableInlineTableEditing", Command::ToggleInlineTableEditor, ExecCommandParam::Boolean, SetDocumentStateCommand::GetInstance)); sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("enableAbsolutePositionEditing"), + u"enableAbsolutePositionEditing"_ns, InternalCommandData( "cmd_enableAbsolutePositionEditing", Command::ToggleAbsolutePositionEditor, @@ -4516,7 +4514,7 @@ void Document::EnsureInitializeInternalCommandDataHashtable() { #if 0 // with empty string sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("justifynone"), + u"justifynone"_ns, InternalCommandData( "cmd_align", Command::Undefined, @@ -4524,7 +4522,7 @@ void Document::EnsureInitializeInternalCommandDataHashtable() { nullptr)); // Not implemented yet. // REQUIRED SPECIAL REVIEW special review sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("saveas"), + u"saveas"_ns, InternalCommandData( "cmd_saveAs", Command::Undefined, @@ -4532,7 +4530,7 @@ void Document::EnsureInitializeInternalCommandDataHashtable() { nullptr)); // Not implemented yet. // REQUIRED SPECIAL REVIEW special review sInternalCommandDataHashtable->Put( - NS_LITERAL_STRING("print"), + u"print"_ns, InternalCommandData( "cmd_print", Command::Undefined, @@ -4732,9 +4730,8 @@ bool Document::ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI, if (!nsContentUtils::IsCutCopyAllowed(this, aSubjectPrincipal)) { // We have rejected the event due to it not being performed in an // input-driven context therefore, we report the error to the console. - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DOM"), this, - nsContentUtils::eDOM_PROPERTIES, + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + this, nsContentUtils::eDOM_PROPERTIES, "ExecCommandCutCopyDeniedNotInputDriven"); return false; } @@ -5182,7 +5179,7 @@ void Document::QueryCommandValue(const nsAString& aHTMLCommandName, if (aRv.Failed()) { return; } - aRv = params->SetCString("format", NS_LITERAL_CSTRING("text/html")); + aRv = params->SetCString("format", "text/html"_ns); if (aRv.Failed()) { return; } @@ -5497,8 +5494,7 @@ nsresult Document::EditingStateChanged() { // restricted one. ErrorResult errorResult; nsCOMPtr principal = NodePrincipal(); - Unused << ExecCommand(NS_LITERAL_STRING("insertBrOnReturn"), false, - NS_LITERAL_STRING("false"), + Unused << ExecCommand(u"insertBrOnReturn"_ns, false, u"false"_ns, // Principal doesn't matter here, because the // insertBrOnReturn command doesn't use it. Still // it's too bad we can't easily grab a nullprincipal @@ -6578,7 +6574,7 @@ void Document::StyleSheetApplicableStateChanged(StyleSheet& aSheet) { RefPtr event = StyleSheetApplicableStateChangeEvent::Constructor( - this, NS_LITERAL_STRING("StyleSheetApplicableStateChanged"), init); + this, u"StyleSheetApplicableStateChanged"_ns, init); event->SetTrusted(true); event->SetTarget(this); RefPtr asyncDispatcher = @@ -7195,8 +7191,8 @@ void Document::DispatchContentLoadedEvents() { // loaded (excluding images and other loads initiated by this // document). nsContentUtils::DispatchTrustedEvent(this, ToSupports(this), - NS_LITERAL_STRING("DOMContentLoaded"), - CanBubble::eYes, Cancelable::eNo); + u"DOMContentLoaded"_ns, CanBubble::eYes, + Cancelable::eNo); if (auto* const window = GetInnerWindow()) { const RefPtr serviceWorker = @@ -7244,13 +7240,11 @@ void Document::DispatchContentLoadedEvents() { RefPtr event; if (parent) { IgnoredErrorResult ignored; - event = parent->CreateEvent(NS_LITERAL_STRING("Events"), - CallerType::System, ignored); + event = parent->CreateEvent(u"Events"_ns, CallerType::System, ignored); } if (event) { - event->InitEvent(NS_LITERAL_STRING("DOMFrameContentLoaded"), true, - true); + event->InitEvent(u"DOMFrameContentLoaded"_ns, true, true); event->SetTarget(target_frame); event->SetTrusted(true); @@ -7280,9 +7274,9 @@ void Document::DispatchContentLoadedEvents() { // event. Element* root = GetRootElement(); if (root && root->HasAttr(kNameSpaceID_None, nsGkAtoms::manifest)) { - nsContentUtils::DispatchChromeEvent( - this, ToSupports(this), NS_LITERAL_STRING("MozApplicationManifest"), - CanBubble::eYes, Cancelable::eYes); + nsContentUtils::DispatchChromeEvent(this, ToSupports(this), + u"MozApplicationManifest"_ns, + CanBubble::eYes, Cancelable::eYes); } nsPIDOMWindowInner* inner = GetInnerWindow(); @@ -7766,7 +7760,7 @@ already_AddRefed Document::CreateCDATASection( return nullptr; } - if (FindInReadable(NS_LITERAL_STRING("]]>"), aData)) { + if (FindInReadable(u"]]>"_ns, aData)) { rv.Throw(NS_ERROR_DOM_INVALID_CHARACTER_ERR); return nullptr; } @@ -7788,7 +7782,7 @@ already_AddRefed Document::CreateProcessingInstruction( return nullptr; } - if (FindInReadable(NS_LITERAL_STRING("?>"), aData)) { + if (FindInReadable(u"?>"_ns, aData)) { rv.Throw(NS_ERROR_DOM_INVALID_CHARACTER_ERR); return nullptr; } @@ -8075,8 +8069,7 @@ void Document::SetDomain(const nsAString& aDomain, ErrorResult& rv) { return; } - if (!FeaturePolicyUtils::IsFeatureAllowed( - this, NS_LITERAL_STRING("document-domain"))) { + if (!FeaturePolicyUtils::IsFeatureAllowed(this, u"document-domain"_ns)) { rv.Throw(NS_ERROR_DOM_SECURITY_ERR); return; } @@ -8421,8 +8414,8 @@ void Document::DoNotifyPossibleTitleChange() { // Fire a DOM event for the title change. nsContentUtils::DispatchChromeEvent(this, ToSupports(this), - NS_LITERAL_STRING("DOMTitleChanged"), - CanBubble::eYes, Cancelable::eYes); + u"DOMTitleChanged"_ns, CanBubble::eYes, + Cancelable::eYes); } already_AddRefed Document::MatchMedia( @@ -9058,7 +9051,7 @@ void Document::WriteCommon(const nsAString& aText, bool aNewlineTerminate, if (mIgnoreDestructiveWritesCounter) { // Instead of implying a call to document.open(), ignore the call. nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Events"), this, + nsIScriptError::warningFlag, "DOM Events"_ns, this, nsContentUtils::eDOM_PROPERTIES, "DocumentWriteIgnored"); return; } @@ -9075,7 +9068,7 @@ void Document::WriteCommon(const nsAString& aText, bool aNewlineTerminate, if (mIgnoreDestructiveWritesCounter) { // Instead of implying a call to document.open(), ignore the call. nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Events"), this, + nsIScriptError::warningFlag, "DOM Events"_ns, this, nsContentUtils::eDOM_PROPERTIES, "DocumentWriteIgnored"); return; } @@ -9889,9 +9882,9 @@ void Document::AddMetaViewportElement(HTMLMetaElement* aElement, // Trigger recomputation of the nsViewportInfo the next time it's queried. mViewportType = Unknown; - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("DOMMetaViewportFitChanged"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"DOMMetaViewportFitChanged"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->RunDOMEventWhenSafe(); } @@ -9902,9 +9895,9 @@ void Document::RemoveMetaViewportElement(HTMLMetaElement* aElement) { // Trigger recomputation of the nsViewportInfo the next time it's queried. mViewportType = Unknown; - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("DOMMetaViewportFitChanged"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"DOMMetaViewportFitChanged"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->RunDOMEventWhenSafe(); return; } @@ -10143,8 +10136,7 @@ void Document::RetrieveRelevantHeaders(nsIChannel* aChannel) { if (httpChannel) { nsAutoCString tmp; - rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("last-modified"), - tmp); + rv = httpChannel->GetResponseHeader("last-modified"_ns, tmp); if (NS_SUCCEEDED(rv)) { PRTime time; @@ -10252,8 +10244,7 @@ void Document::Sanitize() { // First locate all input elements, regardless of whether they are // in a form, and reset the password and autocomplete=off elements. - RefPtr nodes = - GetElementsByTagName(NS_LITERAL_STRING("input")); + RefPtr nodes = GetElementsByTagName(u"input"_ns); nsAutoString value; @@ -10272,7 +10263,7 @@ void Document::Sanitize() { } // Now locate all _form_ elements that have autocomplete=off and reset them - nodes = GetElementsByTagName(NS_LITERAL_STRING("form")); + nodes = GetElementsByTagName(u"form"_ns); length = nodes->Length(true); for (uint32_t i = 0; i < length; ++i) { @@ -10685,9 +10676,9 @@ void Document::UnblockOnload(bool aFireSync) { // event to indicate that the SVG should be considered fully loaded. // Because scripting is disabled on SVG-as-image documents, this event // is not accessible to content authors. (See bug 837315.) - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), CanBubble::eNo, - ChromeOnlyDispatch::eNo); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"MozSVGAsImageDocumentLoad"_ns, + CanBubble::eNo, ChromeOnlyDispatch::eNo); asyncDispatcher->PostDOMEvent(); } } @@ -10801,7 +10792,7 @@ void Document::OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget, if (aPersisted && root) { // Send out notifications that our elements are attached. RefPtr links = - NS_GetContentList(root, kNameSpaceID_XHTML, NS_LITERAL_STRING("link")); + NS_GetContentList(root, kNameSpaceID_XHTML, u"link"_ns); uint32_t linkCount = links->Length(true); for (uint32_t i = 0; i < linkCount; ++i) { @@ -10850,8 +10841,8 @@ void Document::OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget, if (!target) { target = do_QueryInterface(GetWindow()); } - DispatchPageTransition(target, NS_LITERAL_STRING("pageshow"), - inFrameLoaderSwap, aPersisted, aOnlySystemGroup); + DispatchPageTransition(target, u"pageshow"_ns, inFrameLoaderSwap, + aPersisted, aOnlySystemGroup); } } @@ -10878,7 +10869,7 @@ void Document::OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget, Element* root = GetRootElement(); if (aPersisted && root) { RefPtr links = - NS_GetContentList(root, kNameSpaceID_XHTML, NS_LITERAL_STRING("link")); + NS_GetContentList(root, kNameSpaceID_XHTML, u"link"_ns); uint32_t linkCount = links->Length(true); for (uint32_t i = 0; i < linkCount; ++i) { @@ -10924,8 +10915,8 @@ void Document::OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget, } { PageUnloadingEventTimeStamp timeStamp(this); - DispatchPageTransition(target, NS_LITERAL_STRING("pagehide"), - inFrameLoaderSwap, aPersisted, aOnlySystemGroup); + DispatchPageTransition(target, u"pagehide"_ns, inFrameLoaderSwap, + aPersisted, aOnlySystemGroup); } } @@ -11257,9 +11248,8 @@ void Document::SetReadyStateInternal(ReadyState aReadyState, RecordNavigationTiming(aReadyState); } - RefPtr asyncDispatcher = - new AsyncEventDispatcher(this, NS_LITERAL_STRING("readystatechange"), - CanBubble::eNo, ChromeOnlyDispatch::eNo); + RefPtr asyncDispatcher = new AsyncEventDispatcher( + this, u"readystatechange"_ns, CanBubble::eNo, ChromeOnlyDispatch::eNo); asyncDispatcher->RunDOMEventWhenSafe(); } @@ -11419,8 +11409,8 @@ void Document::PreLoadImage(nsIURI* aUri, const nsAString& aCrossOriginAttr, nsresult rv = nsContentUtils::LoadImage( aUri, static_cast(this), this, NodePrincipal(), 0, referrerInfo, nullptr /* no observer */, loadFlags, - aLinkPreload ? NS_LITERAL_STRING("link") : NS_LITERAL_STRING("img"), - getter_AddRefs(request), policyType, false /* urgent */, aLinkPreload); + aLinkPreload ? u"link"_ns : u"img"_ns, getter_AddRefs(request), + policyType, false /* urgent */, aLinkPreload); // Pin image-reference to avoid evicting it from the img-cache before // the "real" load occurs. Unpinned in DispatchContentLoadedEvents and @@ -11473,9 +11463,9 @@ void Document::MaybePreconnect(nsIURI* aOrigURI, mozilla::CORSMode aCORSMode) { // normalize the path before putting it in the hash to accomplish that. if (aCORSMode == CORS_ANONYMOUS) { - mutator.SetPathQueryRef(NS_LITERAL_CSTRING("/anonymous")); + mutator.SetPathQueryRef("/anonymous"_ns); } else { - mutator.SetPathQueryRef(NS_LITERAL_CSTRING("/")); + mutator.SetPathQueryRef("/"_ns); } nsCOMPtr uri; @@ -12262,7 +12252,7 @@ void Document::WarnOnceAbout( } uint32_t flags = asError ? nsIScriptError::errorFlag : nsIScriptError::warningFlag; - nsContentUtils::ReportToConsole(flags, NS_LITERAL_CSTRING("DOM Core"), this, + nsContentUtils::ReportToConsole(flags, "DOM Core"_ns, this, nsContentUtils::eDOM_PROPERTIES, kDeprecationWarnings[aOperation], aParams); } @@ -12281,7 +12271,7 @@ void Document::WarnOnceAbout( mDocWarningWarnedAbout[aWarning] = true; uint32_t flags = asError ? nsIScriptError::errorFlag : nsIScriptError::warningFlag; - nsContentUtils::ReportToConsole(flags, NS_LITERAL_CSTRING("DOM Core"), this, + nsContentUtils::ReportToConsole(flags, "DOM Core"_ns, this, nsContentUtils::eDOM_PROPERTIES, kDocumentWarnings[aWarning], aParams); } @@ -12805,9 +12795,9 @@ void Document::MaybeWarnAboutZoom() { } mHasWarnedAboutZoom = true; - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Layout"), this, - nsContentUtils::eLAYOUT_PROPERTIES, "ZoomPropertyWarning"); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Layout"_ns, + this, nsContentUtils::eLAYOUT_PROPERTIES, + "ZoomPropertyWarning"); } nsIHTMLCollection* Document::Children() { @@ -13076,8 +13066,8 @@ already_AddRefed Document::ExitFullscreen(ErrorResult& aRv) { static void AskWindowToExitFullscreen(Document* aDoc) { if (XRE_GetProcessType() == GeckoProcessType_Content) { nsContentUtils::DispatchEventOnlyToChrome( - aDoc, ToSupports(aDoc), NS_LITERAL_STRING("MozDOMFullscreen:Exit"), - CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr); + aDoc, ToSupports(aDoc), u"MozDOMFullscreen:Exit"_ns, CanBubble::eYes, + Cancelable::eNo, /* DefaultAction */ nullptr); } else { if (nsPIDOMWindowOuter* win = aDoc->GetWindow()) { win->SetFullscreenInternal(FullscreenReason::ForFullscreenAPI, false); @@ -13190,7 +13180,7 @@ class ExitFullscreenScriptRunnable : public Runnable { // document since we want this event to follow the same path that // MozDOMFullscreen:Entered was dispatched. nsContentUtils::DispatchEventOnlyToChrome( - mLeaf, ToSupports(mLeaf), NS_LITERAL_STRING("MozDOMFullscreen:Exited"), + mLeaf, ToSupports(mLeaf), u"MozDOMFullscreen:Exited"_ns, CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr); // Ensure the window exits fullscreen. if (nsPIDOMWindowOuter* win = mRoot->GetWindow()) { @@ -13253,9 +13243,9 @@ void Document::ExitFullscreenInDocTree(Document* aMaybeNotARootDoc) { } static void DispatchFullscreenNewOriginEvent(Document* aDoc) { - RefPtr asyncDispatcher = new AsyncEventDispatcher( - aDoc, NS_LITERAL_STRING("MozDOMFullscreen:NewOrigin"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(aDoc, u"MozDOMFullscreen:NewOrigin"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->PostDOMEvent(); } @@ -13640,8 +13630,7 @@ const char* Document::GetFullscreenError(CallerType aCallerType) { return "FullscreenDeniedHidden"; } - if (!FeaturePolicyUtils::IsFeatureAllowed(this, - NS_LITERAL_STRING("fullscreen"))) { + if (!FeaturePolicyUtils::IsFeatureAllowed(this, u"fullscreen"_ns)) { return "FullscreenDeniedFeaturePolicy"; } @@ -13797,8 +13786,8 @@ void Document::RequestFullscreenInContentProcess( // If we are not the top level process, dispatch an event to make // our parent process go fullscreen first. nsContentUtils::DispatchEventOnlyToChrome( - this, ToSupports(this), NS_LITERAL_STRING("MozDOMFullscreen:Request"), - CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr); + this, ToSupports(this), u"MozDOMFullscreen:Request"_ns, CanBubble::eYes, + Cancelable::eNo, /* DefaultAction */ nullptr); } void Document::RequestFullscreenInParentProcess( @@ -13946,8 +13935,8 @@ bool Document::ApplyFullscreen(UniquePtr aRequest) { // to pop up warning UI. if (!previousFullscreenDoc) { nsContentUtils::DispatchEventOnlyToChrome( - this, ToSupports(elem), NS_LITERAL_STRING("MozDOMFullscreen:Entered"), - CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr); + this, ToSupports(elem), u"MozDOMFullscreen:Entered"_ns, CanBubble::eYes, + Cancelable::eNo, /* DefaultAction */ nullptr); } // The origin which is fullscreen gets changed. Trigger an event so @@ -13991,7 +13980,7 @@ static void DispatchPointerLockChange(Document* aTarget) { } RefPtr asyncDispatcher = - new AsyncEventDispatcher(aTarget, NS_LITERAL_STRING("pointerlockchange"), + new AsyncEventDispatcher(aTarget, u"pointerlockchange"_ns, CanBubble::eYes, ChromeOnlyDispatch::eNo); asyncDispatcher->PostDOMEvent(); } @@ -14002,12 +13991,12 @@ static void DispatchPointerLockError(Document* aTarget, const char* aMessage) { } RefPtr asyncDispatcher = - new AsyncEventDispatcher(aTarget, NS_LITERAL_STRING("pointerlockerror"), - CanBubble::eYes, ChromeOnlyDispatch::eNo); + new AsyncEventDispatcher(aTarget, u"pointerlockerror"_ns, CanBubble::eYes, + ChromeOnlyDispatch::eNo); asyncDispatcher->PostDOMEvent(); - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DOM"), aTarget, - nsContentUtils::eDOM_PROPERTIES, aMessage); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + aTarget, nsContentUtils::eDOM_PROPERTIES, + aMessage); } class PointerLockRequest final : public Runnable { @@ -14150,8 +14139,8 @@ PointerLockRequest::Run() { ChangePointerLockedElement(e, doc, nullptr); nsContentUtils::DispatchEventOnlyToChrome( - doc, ToSupports(e), NS_LITERAL_STRING("MozDOMPointerLock:Entered"), - CanBubble::eYes, Cancelable::eNo, /* DefaultAction */ nullptr); + doc, ToSupports(e), u"MozDOMPointerLock:Entered"_ns, CanBubble::eYes, + Cancelable::eNo, /* DefaultAction */ nullptr); return NS_OK; } @@ -14247,8 +14236,8 @@ void Document::UnlockPointer(Document* aDoc) { ChangePointerLockedElement(nullptr, pointerLockedDoc, pointerLockedElement); RefPtr asyncDispatcher = new AsyncEventDispatcher( - pointerLockedElement, NS_LITERAL_STRING("MozDOMPointerLock:Exited"), - CanBubble::eYes, ChromeOnlyDispatch::eYes); + pointerLockedElement, u"MozDOMPointerLock:Exited"_ns, CanBubble::eYes, + ChromeOnlyDispatch::eYes); asyncDispatcher->RunDOMEventWhenSafe(); } @@ -14257,7 +14246,7 @@ void Document::UpdateVisibilityState() { mVisibilityState = ComputeVisibilityState(); if (oldState != mVisibilityState) { nsContentUtils::DispatchTrustedEvent(this, ToSupports(this), - NS_LITERAL_STRING("visibilitychange"), + u"visibilitychange"_ns, CanBubble::eYes, Cancelable::eNo); EnumerateActivityObservers(NotifyActivityChanged); } @@ -15110,7 +15099,7 @@ void Document::ReportHasScrollLinkedEffect() { } mHasScrollLinkedEffect = true; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Async Pan/Zoom"), this, + nsIScriptError::warningFlag, "Async Pan/Zoom"_ns, this, nsContentUtils::eLAYOUT_PROPERTIES, "ScrollLinkedEffectFound2"); } @@ -15399,7 +15388,7 @@ class UserIntractionTimer final : public Runnable, NS_ENSURE_TRUE(!!phase, NS_OK); rv = phase->AddBlocker(this, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("UserIntractionTimer shutdown")); + u"UserIntractionTimer shutdown"_ns); NS_ENSURE_SUCCESS(rv, NS_OK); raii.release(); @@ -16242,10 +16231,10 @@ void Document::ReportShadowDOMUsage() { nsString uri; Unused << topLevel->GetDocumentURI(uri); if (!uri.IsEmpty()) { - nsAutoString msg = NS_LITERAL_STRING("Shadow DOM used in [") + uri + - NS_LITERAL_STRING("] or in some of its subdocuments."); - nsContentUtils::ReportToConsoleNonLocalized( - msg, nsIScriptError::infoFlag, NS_LITERAL_CSTRING("DOM"), topLevel); + nsAutoString msg = u"Shadow DOM used in ["_ns + uri + + u"] or in some of its subdocuments."_ns; + nsContentUtils::ReportToConsoleNonLocalized(msg, nsIScriptError::infoFlag, + "DOM"_ns, topLevel); } } diff --git a/dom/base/Element.cpp b/dom/base/Element.cpp index f2a452e24a60..628dd153f4a7 100644 --- a/dom/base/Element.cpp +++ b/dom/base/Element.cpp @@ -1112,7 +1112,7 @@ already_AddRefed Element::AttachShadowWithoutNameChecks( // Dispatch a "shadowrootattached" event for devtools. { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("shadowrootattached"), CanBubble::eYes, + this, u"shadowrootattached"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes, Composed::eYes); dispatcher->PostDOMEvent(); } @@ -1157,9 +1157,9 @@ void Element::NotifyUAWidgetSetupOrChange() { MOZ_ASSERT(self->GetShadowRoot() && self->GetShadowRoot()->IsUAWidget()); - nsContentUtils::DispatchChromeEvent( - ownerDoc, self, NS_LITERAL_STRING("UAWidgetSetupOrChange"), - CanBubble::eYes, Cancelable::eNo); + nsContentUtils::DispatchChromeEvent(ownerDoc, self, + u"UAWidgetSetupOrChange"_ns, + CanBubble::eYes, Cancelable::eNo); })); } @@ -1186,8 +1186,8 @@ void Element::NotifyUAWidgetTeardown(UnattachShadowRoot aUnattachShadowRoot) { } nsresult rv = nsContentUtils::DispatchChromeEvent( - ownerDoc, self, NS_LITERAL_STRING("UAWidgetTeardown"), - CanBubble::eYes, Cancelable::eNo); + ownerDoc, self, u"UAWidgetTeardown"_ns, CanBubble::eYes, + Cancelable::eNo); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -1699,9 +1699,9 @@ void Element::UnbindFromTree(bool aNullParent) { if (mState.HasState(NS_EVENT_STATE_FULLSCREEN)) { // The element being removed is an ancestor of the fullscreen element, // exit fullscreen state. - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), OwnerDoc(), - nsContentUtils::eDOM_PROPERTIES, "RemovedFullscreenElement"); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, + "RemovedFullscreenElement"); // Fully exit fullscreen. Document::ExitFullscreenInDocTree(OwnerDoc()); } diff --git a/dom/base/EventSource.cpp b/dom/base/EventSource.cpp index 6af942e03cd3..7cb5611c088e 100644 --- a/dom/base/EventSource.cpp +++ b/dom/base/EventSource.cpp @@ -401,7 +401,7 @@ class CleanupRunnable final : public WorkerMainThreadRunnable { public: explicit CleanupRunnable(EventSourceImpl* aEventSourceImpl) : WorkerMainThreadRunnable(GetCurrentThreadWorkerPrivate(), - NS_LITERAL_CSTRING("EventSource :: Cleanup")), + "EventSource :: Cleanup"_ns), mImpl(aEventSourceImpl) { mWorkerPrivate->AssertIsOnWorkerThread(); } @@ -492,8 +492,7 @@ class InitRunnable final : public WorkerMainThreadRunnable { public: InitRunnable(WorkerPrivate* aWorkerPrivate, EventSourceImpl* aEventSourceImpl, const nsAString& aURL) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("EventSource :: Init")), + : WorkerMainThreadRunnable(aWorkerPrivate, "EventSource :: Init"_ns), mImpl(aEventSourceImpl), mURL(aURL), mRv(NS_ERROR_NOT_INITIALIZED) { @@ -534,8 +533,7 @@ class ConnectRunnable final : public WorkerMainThreadRunnable { public: explicit ConnectRunnable(WorkerPrivate* aWorkerPrivate, EventSourceImpl* aEventSourceImpl) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("EventSource :: Connect")), + : WorkerMainThreadRunnable(aWorkerPrivate, "EventSource :: Connect"_ns), mImpl(aEventSourceImpl) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); @@ -971,14 +969,13 @@ nsresult EventSourceImpl::GetBaseURI(nsIURI** aBaseURI) { void EventSourceImpl::SetupHttpChannel() { AssertIsOnMainThread(); MOZ_ASSERT(!IsShutDown()); - nsresult rv = mHttpChannel->SetRequestMethod(NS_LITERAL_CSTRING("GET")); + nsresult rv = mHttpChannel->SetRequestMethod("GET"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); /* set the http request headers */ - rv = mHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), - NS_LITERAL_CSTRING(TEXT_EVENT_STREAM), - false); + rv = mHttpChannel->SetRequestHeader( + "Accept"_ns, nsLiteralCString(TEXT_EVENT_STREAM), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); // LOAD_BYPASS_CACHE already adds the Cache-Control: no-cache header @@ -987,8 +984,7 @@ void EventSourceImpl::SetupHttpChannel() { return; } NS_ConvertUTF16toUTF8 eventId(mLastEventID); - rv = mHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Last-Event-ID"), - eventId, false); + rv = mHttpChannel->SetRequestHeader("Last-Event-ID"_ns, eventId, false); #ifdef DEBUG if (NS_FAILED(rv)) { MOZ_LOG(gEventSourceLog, LogLevel::Warning, @@ -1117,7 +1113,7 @@ void EventSourceImpl::AnnounceConnection() { if (NS_FAILED(rv)) { return; } - rv = mEventSource->CreateAndDispatchSimpleEvent(NS_LITERAL_STRING("open")); + rv = mEventSource->CreateAndDispatchSimpleEvent(u"open"_ns); if (NS_FAILED(rv)) { NS_WARNING("Failed to dispatch the error event!!!"); return; @@ -1145,9 +1141,8 @@ void EventSourceImpl::ResetDecoder() { class CallRestartConnection final : public WorkerMainThreadRunnable { public: explicit CallRestartConnection(EventSourceImpl* aEventSourceImpl) - : WorkerMainThreadRunnable( - aEventSourceImpl->mWorkerRef->Private(), - NS_LITERAL_CSTRING("EventSource :: RestartConnection")), + : WorkerMainThreadRunnable(aEventSourceImpl->mWorkerRef->Private(), + "EventSource :: RestartConnection"_ns), mImpl(aEventSourceImpl) { mWorkerPrivate->AssertIsOnWorkerThread(); } @@ -1202,7 +1197,7 @@ void EventSourceImpl::ReestablishConnection() { SetReadyState(CONNECTING); ResetDecoder(); - rv = mEventSource->CreateAndDispatchSimpleEvent(NS_LITERAL_STRING("error")); + rv = mEventSource->CreateAndDispatchSimpleEvent(u"error"_ns); if (NS_FAILED(rv)) { NS_WARNING("Failed to dispatch the error event!!!"); return; @@ -1325,7 +1320,7 @@ void EventSourceImpl::FailConnection() { // named error at the EventSource object. nsresult rv = mEventSource->CheckCurrentGlobalCorrectness(); if (NS_SUCCEEDED(rv)) { - rv = mEventSource->CreateAndDispatchSimpleEvent(NS_LITERAL_STRING("error")); + rv = mEventSource->CreateAndDispatchSimpleEvent(u"error"_ns); if (NS_FAILED(rv)) { NS_WARNING("Failed to dispatch the error event!!!"); } diff --git a/dom/base/FormData.cpp b/dom/base/FormData.cpp index 31dbc34bb548..0095417efda4 100644 --- a/dom/base/FormData.cpp +++ b/dom/base/FormData.cpp @@ -39,7 +39,7 @@ already_AddRefed GetOrCreateFileCalledBlob(Blob& aBlob, } // Forcing 'blob' as filename - file = aBlob.ToFile(NS_LITERAL_STRING("blob"), aRv); + file = aBlob.ToFile(u"blob"_ns, aRv); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } diff --git a/dom/base/FullscreenChange.h b/dom/base/FullscreenChange.h index 4abfa082fd9c..ed2770527d58 100644 --- a/dom/base/FullscreenChange.h +++ b/dom/base/FullscreenChange.h @@ -103,9 +103,9 @@ class FullscreenRequest : public FullscreenChange { std::move(pendingEvent)); } MayRejectPromise("Fullscreen request denied"); - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DOM"), Document(), - nsContentUtils::eDOM_PROPERTIES, aReason); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + Document(), nsContentUtils::eDOM_PROPERTIES, + aReason); } private: diff --git a/dom/base/ImageEncoder.cpp b/dom/base/ImageEncoder.cpp index e2ca01d7498f..2fda68b66dc9 100644 --- a/dom/base/ImageEncoder.cpp +++ b/dom/base/ImageEncoder.cpp @@ -433,7 +433,7 @@ already_AddRefed ImageEncoder::GetImageEncoder(nsAString& aType) { encoderCID += encoderType; nsCOMPtr encoder = do_CreateInstance(encoderCID.get()); - if (!encoder && aType != NS_LITERAL_STRING("image/png")) { + if (!encoder && aType != u"image/png"_ns) { // Unable to create an encoder instance of the specified type. Falling back // to PNG. aType.AssignLiteral("image/png"); diff --git a/dom/base/InProcessBrowserChildMessageManager.cpp b/dom/base/InProcessBrowserChildMessageManager.cpp index 1dd012edb236..aa2e1b022451 100644 --- a/dom/base/InProcessBrowserChildMessageManager.cpp +++ b/dom/base/InProcessBrowserChildMessageManager.cpp @@ -212,7 +212,7 @@ void InProcessBrowserChildMessageManager::FireUnloadEvent() { // Don't let the unload event propagate to chrome event handlers. mPreventEventsEscaping = true; - DOMEventTargetHelper::DispatchTrustedEvent(NS_LITERAL_STRING("unload")); + DOMEventTargetHelper::DispatchTrustedEvent(u"unload"_ns); // Allow events fired during docshell destruction (pagehide, unload) to // propagate to the element since chrome code depends on this. diff --git a/dom/base/MaybeCrossOriginObject.cpp b/dom/base/MaybeCrossOriginObject.cpp index cadbe6695f83..8b222a52c575 100644 --- a/dom/base/MaybeCrossOriginObject.cpp +++ b/dom/base/MaybeCrossOriginObject.cpp @@ -118,7 +118,7 @@ bool MaybeCrossOriginObjectMixins::CrossOriginPropertyFallback( } // Step 2. - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("access")); + return ReportCrossOriginDenial(cx, id, "access"_ns); } /* static */ @@ -173,7 +173,7 @@ bool MaybeCrossOriginObjectMixins::CrossOriginGet( JS::Rooted getter(cx); if (!desc.hasGetterObject() || !(getter = desc.getterObject())) { // Step 6. - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("get")); + return ReportCrossOriginDenial(cx, id, "get"_ns); } // Step 7. @@ -229,7 +229,7 @@ bool MaybeCrossOriginObjectMixins::CrossOriginSet( } // Step 4. - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("set")); + return ReportCrossOriginDenial(cx, id, "set"_ns); } /* static */ @@ -432,7 +432,7 @@ bool MaybeCrossOriginObject::defineProperty( JSContext* cx, JS::Handle proxy, JS::Handle id, JS::Handle desc, JS::ObjectOpResult& result) const { if (!IsPlatformObjectSameOrigin(cx, proxy)) { - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("define")); + return ReportCrossOriginDenial(cx, id, "define"_ns); } // Enter the Realm of proxy and do the remaining work in there. diff --git a/dom/base/Navigator.cpp b/dom/base/Navigator.cpp index ed2800a9a7a6..8bc4b5800a49 100644 --- a/dom/base/Navigator.cpp +++ b/dom/base/Navigator.cpp @@ -115,8 +115,7 @@ namespace mozilla { namespace dom { -static const nsLiteralCString kVibrationPermissionType = - NS_LITERAL_CSTRING("vibration"); +static const nsLiteralCString kVibrationPermissionType = "vibration"_ns; Navigator::Navigator(nsPIDOMWindowInner* aWindow) : mWindow(aWindow) {} @@ -589,7 +588,7 @@ void Navigator::GetBuildID(nsAString& aBuildID, CallerType aCallerType, } // Spoof the buildID on pages not loaded from "https://*.mozilla.org". - if (!isHTTPS || !StringEndsWith(host, NS_LITERAL_CSTRING(".mozilla.org"))) { + if (!isHTTPS || !StringEndsWith(host, ".mozilla.org"_ns)) { aBuildID.AssignLiteral(LEGACY_BUILD_ID); return; } @@ -895,7 +894,7 @@ void Navigator::CheckProtocolHandlerAllowed(const nsAString& aScheme, aHandlerURI->GetSpec(spec); // If the uri doesn't contain '%s', it won't be a good handler - the %s // gets replaced with the handled URI. - if (!FindInReadable(NS_LITERAL_CSTRING("%s"), spec)) { + if (!FindInReadable("%s"_ns, spec)) { aRv.ThrowSyntaxError("Handler URI does not contain \"%s\"."); return; } @@ -925,7 +924,7 @@ void Navigator::CheckProtocolHandlerAllowed(const nsAString& aScheme, // Having checked the handler URI, check the scheme: nsAutoCString scheme; ToLowerCase(NS_ConvertUTF16toUTF8(aScheme), scheme); - if (StringBeginsWith(scheme, NS_LITERAL_CSTRING("web+"))) { + if (StringBeginsWith(scheme, "web+"_ns)) { // Check for non-ascii nsReadingIterator iter; nsReadingIterator iterEnd; @@ -998,8 +997,8 @@ void Navigator::RegisterProtocolHandler(const nsAString& aScheme, // If we're a private window, don't alert the user or webpage. We log to the // console so that web developers have some way to tell what's going wrong. nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), - mWindow->GetDoc(), nsContentUtils::eDOM_PROPERTIES, + nsIScriptError::warningFlag, "DOM"_ns, mWindow->GetDoc(), + nsContentUtils::eDOM_PROPERTIES, "RegisterProtocolHandlerPrivateBrowsingWarning"); return; } @@ -1186,8 +1185,8 @@ bool Navigator::SendBeaconInternal(const nsAString& aUrl, // Ensure that only streams with content types that are safelisted ignore CORS // rules if (aBody && !contentTypeWithCharset.IsVoid() && - !nsContentUtils::IsCORSSafelistedRequestHeader( - NS_LITERAL_CSTRING("content-type"), contentTypeWithCharset)) { + !nsContentUtils::IsCORSSafelistedRequestHeader("content-type"_ns, + contentTypeWithCharset)) { securityFlags |= nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS; } else { securityFlags |= nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_INHERITS; @@ -1221,9 +1220,9 @@ bool Navigator::SendBeaconInternal(const nsAString& aUrl, } uploadChannel->ExplicitSetUploadStream(in, contentTypeWithCharset, length, - NS_LITERAL_CSTRING("POST"), false); + "POST"_ns, false); } else { - rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChannel->SetRequestMethod("POST"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -1483,14 +1482,13 @@ void Navigator::GetGamepads(nsTArray>& aGamepads, // show a console warning to developers. if (!mGamepadSecureContextWarningShown && !win->IsSecureContext()) { mGamepadSecureContextWarningShown = true; - auto msg = NS_LITERAL_STRING( - "The Gamepad API is only available in " + auto msg = + u"The Gamepad API is only available in " "secure contexts (e.g., https). Please see " "https://hacks.mozilla.org/2020/06/securing-gamepad-api/ for more " - "info."); + "info."_ns; nsContentUtils::ReportToConsoleNonLocalized( - msg, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), - win->GetExtantDoc()); + msg, nsIScriptError::warningFlag, "DOM"_ns, win->GetExtantDoc()); } #ifdef NIGHTLY_BUILD @@ -1517,7 +1515,7 @@ already_AddRefed Navigator::GetVRDisplays(ErrorResult& aRv) { } if (!FeaturePolicyUtils::IsFeatureAllowed(mWindow->GetExtantDoc(), - NS_LITERAL_STRING("vr"))) { + u"vr"_ns)) { aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); return nullptr; } @@ -1995,8 +1993,7 @@ nsresult Navigator::GetUserAgent(nsPIDOMWindowInner* aWindow, nsCOMPtr httpChannel = do_QueryInterface(doc->GetChannel()); if (httpChannel) { nsAutoCString userAgent; - rv = httpChannel->GetRequestHeader(NS_LITERAL_CSTRING("User-Agent"), - userAgent); + rv = httpChannel->GetRequestHeader("User-Agent"_ns, userAgent); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2033,22 +2030,21 @@ already_AddRefed Navigator::RequestMediaKeySystemAccess( if (doc) { Unused << doc->GetDocumentURI(*uri); } - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Media"), doc, - nsContentUtils::eDOM_PROPERTIES, - "MediaEMEInsecureContextDeprecatedWarning", params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Media"_ns, + doc, nsContentUtils::eDOM_PROPERTIES, + "MediaEMEInsecureContextDeprecatedWarning", + params); } Document* doc = mWindow->GetExtantDoc(); - if (doc && !FeaturePolicyUtils::IsFeatureAllowed( - doc, NS_LITERAL_STRING("encrypted-media"))) { + if (doc && + !FeaturePolicyUtils::IsFeatureAllowed(doc, u"encrypted-media"_ns)) { aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); return nullptr; } RefPtr promise = DetailedPromise::Create( - mWindow->AsGlobal(), aRv, - NS_LITERAL_CSTRING("navigator.requestMediaKeySystemAccess"), + mWindow->AsGlobal(), aRv, "navigator.requestMediaKeySystemAccess"_ns, Telemetry::VIDEO_EME_REQUEST_SUCCESS_LATENCY_MS, Telemetry::VIDEO_EME_REQUEST_FAILURE_LATENCY_MS); if (aRv.Failed()) { diff --git a/dom/base/NodeInfo.cpp b/dom/base/NodeInfo.cpp index c678fd755f47..9ce5faf734d2 100644 --- a/dom/base/NodeInfo.cpp +++ b/dom/base/NodeInfo.cpp @@ -62,8 +62,7 @@ NodeInfo::NodeInfo(nsAtom* aName, nsAtom* aPrefix, int32_t aNamespaceID, // Qualified name. If we have no prefix, use ToString on // mInner.mName so that we get to share its buffer. if (aPrefix) { - mQualifiedName = nsDependentAtomString(mInner.mPrefix) + - NS_LITERAL_STRING(":") + + mQualifiedName = nsDependentAtomString(mInner.mPrefix) + u":"_ns + nsDependentAtomString(mInner.mName); } else { mInner.mName->ToString(mQualifiedName); diff --git a/dom/base/PopupBlocker.cpp b/dom/base/PopupBlocker.cpp index 0af75e6bf8ba..83ce98460c78 100644 --- a/dom/base/PopupBlocker.cpp +++ b/dom/base/PopupBlocker.cpp @@ -127,7 +127,7 @@ bool PopupBlocker::CanShowPopupByPermission(nsIPrincipal* aPrincipal) { if (permissionManager && NS_SUCCEEDED(permissionManager->TestPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("popup"), &permit))) { + aPrincipal, "popup"_ns, &permit))) { if (permit == nsIPermissionManager::ALLOW_ACTION) { return true; } diff --git a/dom/base/PostMessageEvent.cpp b/dom/base/PostMessageEvent.cpp index 6b12b81f0f8b..5acc31849c75 100644 --- a/dom/base/PostMessageEvent.cpp +++ b/dom/base/PostMessageEvent.cpp @@ -218,7 +218,7 @@ PostMessageEvent::Run() { return NS_OK; } - event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), CanBubble::eNo, + event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo, Cancelable::eNo, messageData, mCallerOrigin, EmptyString(), source, ports); @@ -238,8 +238,8 @@ void PostMessageEvent::DispatchError(JSContext* aCx, init.mSource.SetValue().SetAsWindowProxy() = mSource; } - RefPtr event = MessageEvent::Constructor( - aEventTarget, NS_LITERAL_STRING("messageerror"), init); + RefPtr event = + MessageEvent::Constructor(aEventTarget, u"messageerror"_ns, init); Dispatch(aTargetWindow, event); } diff --git a/dom/base/RemoteOuterWindowProxy.cpp b/dom/base/RemoteOuterWindowProxy.cpp index 2c92e574d47d..c3ebe8f010aa 100644 --- a/dom/base/RemoteOuterWindowProxy.cpp +++ b/dom/base/RemoteOuterWindowProxy.cpp @@ -99,7 +99,7 @@ bool RemoteOuterWindowProxy::getOwnPropertyDescriptor( return WrapResult(aCx, aProxy, children[index], JSPROP_READONLY | JSPROP_ENUMERATE, aDesc); } - return ReportCrossOriginDenial(aCx, aId, NS_LITERAL_CSTRING("access")); + return ReportCrossOriginDenial(aCx, aId, "access"_ns); } bool ok = CrossOriginGetOwnPropertyHelper(aCx, aProxy, aId, aDesc); diff --git a/dom/base/ScreenOrientation.cpp b/dom/base/ScreenOrientation.cpp index 348889558a99..fd56195ecc5a 100644 --- a/dom/base/ScreenOrientation.cpp +++ b/dom/base/ScreenOrientation.cpp @@ -364,7 +364,7 @@ bool ScreenOrientation::LockDeviceOrientation( mFullscreenListener = new FullscreenEventListener(); } - aRv = target->AddSystemEventListener(NS_LITERAL_STRING("fullscreenchange"), + aRv = target->AddSystemEventListener(u"fullscreenchange"_ns, mFullscreenListener, /* useCapture = */ true); if (NS_WARN_IF(aRv.Failed())) { @@ -390,7 +390,7 @@ void ScreenOrientation::UnlockDeviceOrientation() { // Remove event listener in case of fullscreen lock. nsCOMPtr target = GetOwner()->GetDoc(); if (target) { - target->RemoveSystemEventListener(NS_LITERAL_STRING("fullscreenchange"), + target->RemoveSystemEventListener(u"fullscreenchange"_ns, mFullscreenListener, /* useCapture */ true); } @@ -510,15 +510,14 @@ void ScreenOrientation::Notify(const hal::ScreenConfiguration& aConfiguration) { DebugOnly rv; if (mScreen && mType != previousOrientation) { // Use of mozorientationchange is deprecated. - rv = mScreen->DispatchTrustedEvent( - NS_LITERAL_STRING("mozorientationchange")); + rv = mScreen->DispatchTrustedEvent(u"mozorientationchange"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed"); } if (doc->Hidden() && !mVisibleListener) { mVisibleListener = new VisibleEventListener(); - rv = doc->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"), - mVisibleListener, /* useCapture = */ true); + rv = doc->AddSystemEventListener(u"visibilitychange"_ns, mVisibleListener, + /* useCapture = */ true); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "AddSystemEventListener failed"); return; } @@ -548,8 +547,7 @@ ScreenOrientation::DispatchChangeEventAndResolvePromise() { RefPtr self = this; return NS_NewRunnableFunction( "dom::ScreenOrientation::DispatchChangeEvent", [self, doc]() { - DebugOnly rv = - self->DispatchTrustedEvent(NS_LITERAL_STRING("change")); + DebugOnly rv = self->DispatchTrustedEvent(u"change"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed"); if (doc) { Promise* pendingPromise = doc->GetOrientationPendingPromise(); @@ -603,8 +601,7 @@ ScreenOrientation::VisibleEventListener::HandleEvent(Event* aEvent) { ScreenOrientation* orientation = screen->Orientation(); MOZ_ASSERT(orientation); - target->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"), this, - true); + target->RemoveSystemEventListener(u"visibilitychange"_ns, this, true); BrowsingContext* bc = doc->GetBrowsingContext(); if (bc && bc->GetCurrentOrientationType() != @@ -650,7 +647,6 @@ ScreenOrientation::FullscreenEventListener::HandleEvent(Event* aEvent) { hal::UnlockScreenOrientation(); - target->RemoveSystemEventListener(NS_LITERAL_STRING("fullscreenchange"), this, - true); + target->RemoveSystemEventListener(u"fullscreenchange"_ns, this, true); return NS_OK; } diff --git a/dom/base/Selection.cpp b/dom/base/Selection.cpp index 28653443303e..c63400683b80 100644 --- a/dom/base/Selection.cpp +++ b/dom/base/Selection.cpp @@ -285,8 +285,8 @@ void Selection::Stringify(nsAString& aResult, FlushFrames aFlushFrames) { } IgnoredErrorResult rv; - ToStringWithFormat(NS_LITERAL_STRING("text/plain"), - nsIDocumentEncoder::SkipInvisibleContent, 0, aResult, rv); + ToStringWithFormat(u"text/plain"_ns, nsIDocumentEncoder::SkipInvisibleContent, + 0, aResult, rv); if (rv.Failed()) { aResult.Truncate(); } @@ -806,8 +806,8 @@ static bool MaybeDispatchSelectstartEvent( if (selectstartEventTarget) { nsContentUtils::DispatchTrustedEvent( - aDocument, selectstartEventTarget, NS_LITERAL_STRING("selectstart"), - CanBubble::eYes, Cancelable::eYes, &executeDefaultAction); + aDocument, selectstartEventTarget, u"selectstart"_ns, CanBubble::eYes, + Cancelable::eYes, &executeDefaultAction); } return executeDefaultAction; diff --git a/dom/base/ShadowRoot.h b/dom/base/ShadowRoot.h index 945e5460fc7a..f2fccde8c2b4 100644 --- a/dom/base/ShadowRoot.h +++ b/dom/base/ShadowRoot.h @@ -152,7 +152,7 @@ class ShadowRoot final : public DocumentFragment, void RemoveSlot(HTMLSlotElement* aSlot); bool HasSlots() const { return !mSlotMap.IsEmpty(); }; HTMLSlotElement* GetDefaultSlot() const { - SlotArray* list = mSlotMap.Get(NS_LITERAL_STRING("")); + SlotArray* list = mSlotMap.Get(u""_ns); return list ? (*list)->ElementAt(0) : nullptr; } diff --git a/dom/base/StorageAccessPermissionRequest.cpp b/dom/base/StorageAccessPermissionRequest.cpp index 801643337552..4115ff8fc547 100644 --- a/dom/base/StorageAccessPermissionRequest.cpp +++ b/dom/base/StorageAccessPermissionRequest.cpp @@ -22,8 +22,8 @@ StorageAccessPermissionRequest::StorageAccessPermissionRequest( nsPIDOMWindowInner* aWindow, nsIPrincipal* aNodePrincipal, AllowCallback&& aAllowCallback, CancelCallback&& aCancelCallback) : ContentPermissionRequestBase(aNodePrincipal, aWindow, - NS_LITERAL_CSTRING("dom.storage_access"), - NS_LITERAL_CSTRING("storage-access")), + "dom.storage_access"_ns, + "storage-access"_ns), mAllowCallback(std::move(aAllowCallback)), mCancelCallback(std::move(aCancelCallback)), mCallbackCalled(false) { diff --git a/dom/base/WindowOrientationObserver.cpp b/dom/base/WindowOrientationObserver.cpp index e1118a8f4110..04c858956274 100644 --- a/dom/base/WindowOrientationObserver.cpp +++ b/dom/base/WindowOrientationObserver.cpp @@ -37,8 +37,7 @@ void WindowOrientationObserver::Notify( uint16_t currentAngle = aConfiguration.angle(); if (mAngle != currentAngle && mWindow->IsCurrentInnerWindow()) { mAngle = currentAngle; - mWindow->GetOuterWindow()->DispatchCustomEvent( - NS_LITERAL_STRING("orientationchange")); + mWindow->GetOuterWindow()->DispatchCustomEvent(u"orientationchange"_ns); } } diff --git a/dom/base/XPathGenerator.cpp b/dom/base/XPathGenerator.cpp index ea9df4f01e91..ca0305fe8048 100644 --- a/dom/base/XPathGenerator.cpp +++ b/dom/base/XPathGenerator.cpp @@ -103,15 +103,14 @@ void GenerateConcatExpression(const nsAString& aStr, nsAString& aResult) { } // Prepend concat(' and append '). - aResult.Assign(NS_LITERAL_STRING("concat(\'") + result + - NS_LITERAL_STRING("\')")); + aResult.Assign(u"concat(\'"_ns + result + u"\')"_ns); } void XPathGenerator::QuoteArgument(const nsAString& aArg, nsAString& aResult) { if (!aArg.Contains('\'')) { - aResult.Assign(NS_LITERAL_STRING("\'") + aArg + NS_LITERAL_STRING("\'")); + aResult.Assign(u"\'"_ns + aArg + u"\'"_ns); } else if (!aArg.Contains('\"')) { - aResult.Assign(NS_LITERAL_STRING("\"") + aArg + NS_LITERAL_STRING("\"")); + aResult.Assign(u"\""_ns + aArg + u"\""_ns); } else { GenerateConcatExpression(aArg, aResult); } @@ -121,8 +120,7 @@ void XPathGenerator::EscapeName(const nsAString& aName, nsAString& aResult) { if (ContainNonWordCharacter(aName)) { nsAutoString quotedArg; QuoteArgument(aName, quotedArg); - aResult.Assign(NS_LITERAL_STRING("*[local-name()=") + quotedArg + - NS_LITERAL_STRING("]")); + aResult.Assign(u"*[local-name()="_ns + quotedArg + u"]"_ns); } else { aResult.Assign(aName); } @@ -146,7 +144,7 @@ void XPathGenerator::Generate(const nsINode* aNode, nsAString& aResult) { if (prefix.IsEmpty()) { tag.Assign(nodeEscapeName); } else { - tag.Assign(prefix + NS_LITERAL_STRING(":") + nodeEscapeName); + tag.Assign(prefix + u":"_ns + nodeEscapeName); } if (aNode->HasID()) { @@ -156,8 +154,7 @@ void XPathGenerator::Generate(const nsINode* aNode, nsAString& aResult) { nsAutoString quotedArgument; elem->GetId(elemId); QuoteArgument(elemId, quotedArgument); - aResult.Assign(NS_LITERAL_STRING("//") + tag + NS_LITERAL_STRING("[@id=") + - quotedArgument + NS_LITERAL_STRING("]")); + aResult.Assign(u"//"_ns + tag + u"[@id="_ns + quotedArgument + u"]"_ns); return; } @@ -183,8 +180,7 @@ void XPathGenerator::Generate(const nsINode* aNode, nsAString& aResult) { if (!nodeNameAttribute.IsEmpty()) { nsAutoString quotedArgument; QuoteArgument(nodeNameAttribute, quotedArgument); - namePart.Assign(NS_LITERAL_STRING("[@name=") + quotedArgument + - NS_LITERAL_STRING("]")); + namePart.Assign(u"[@name="_ns + quotedArgument + u"]"_ns); } if (count != 1) { countPart.AssignLiteral(u"["); @@ -192,5 +188,5 @@ void XPathGenerator::Generate(const nsINode* aNode, nsAString& aResult) { countPart.AppendLiteral(u"]"); } Generate(aNode->GetParentNode(), aResult); - aResult.Append(NS_LITERAL_STRING("/") + tag + namePart + countPart); + aResult.Append(u"/"_ns + tag + namePart + countPart); } diff --git a/dom/base/nsAttrValue.cpp b/dom/base/nsAttrValue.cpp index 6a1ae3f5be67..1bb1d11e8ea7 100644 --- a/dom/base/nsAttrValue.cpp +++ b/dom/base/nsAttrValue.cpp @@ -552,7 +552,7 @@ void nsAttrValue::ToString(nsAString& aResult) const { } else { str.AppendInt(GetIntInternal()); } - aResult = str + NS_LITERAL_STRING("%"); + aResult = str + u"%"_ns; break; } diff --git a/dom/base/nsContentAreaDragDrop.cpp b/dom/base/nsContentAreaDragDrop.cpp index b03a3a8432a5..fc1fe8a9bed6 100644 --- a/dom/base/nsContentAreaDragDrop.cpp +++ b/dom/base/nsContentAreaDragDrop.cpp @@ -392,9 +392,8 @@ void DragDataProducer::CreateLinkText(const nsAString& inURL, // use a temp var in case |inText| is the same string as // |outLinkText| to avoid overwriting it while building up the // string in pieces. - nsAutoString linkText(NS_LITERAL_STRING("") + inText + - NS_LITERAL_STRING("")); + nsAutoString linkText(u""_ns + inText + + u""_ns); outLinkText = linkText; } @@ -813,12 +812,13 @@ nsresult DragDataProducer::AddStringsToDataTransfer( dragData += title; AddString(aDataTransfer, NS_LITERAL_STRING(kURLMime), dragData, principal); + AddString(aDataTransfer, NS_LITERAL_STRING(kURLDataMime), mUrlString, + principal); AddString(aDataTransfer, NS_LITERAL_STRING(kURLDataMime), mUrlString, principal); AddString(aDataTransfer, NS_LITERAL_STRING(kURLDescriptionMime), mTitleString, principal); - AddString(aDataTransfer, NS_LITERAL_STRING("text/uri-list"), mUrlString, - principal); + AddString(aDataTransfer, u"text/uri-list"_ns, mUrlString, principal); } // add a special flavor for the html context data @@ -878,8 +878,7 @@ nsresult DragDataProducer::AddStringsToDataTransfer( if (!mIsAnchor) { AddString(aDataTransfer, NS_LITERAL_STRING(kURLDataMime), mUrlString, principal); - AddString(aDataTransfer, NS_LITERAL_STRING("text/uri-list"), mUrlString, - principal); + AddString(aDataTransfer, u"text/uri-list"_ns, mUrlString, principal); } } diff --git a/dom/base/nsContentSink.cpp b/dom/base/nsContentSink.cpp index 23327e8e99d3..ce9d638c3c4f 100644 --- a/dom/base/nsContentSink.cpp +++ b/dom/base/nsContentSink.cpp @@ -229,8 +229,7 @@ nsresult nsContentSink::ProcessHTTPHeaders(nsIChannel* aChannel) { nsAutoCString linkHeader; - nsresult rv = - httpchannel->GetResponseHeader(NS_LITERAL_CSTRING("link"), linkHeader); + nsresult rv = httpchannel->GetResponseHeader("link"_ns, linkHeader); if (NS_SUCCEEDED(rv) && !linkHeader.IsEmpty()) { mDocument->SetHeaderData(nsGkAtoms::link, NS_ConvertASCIItoUTF16(linkHeader)); @@ -832,7 +831,7 @@ void nsContentSink::PrefetchDNS(const nsAString& aHref) { nsAutoString hostname; bool isHttps = false; - if (StringBeginsWith(aHref, NS_LITERAL_STRING("//"))) { + if (StringBeginsWith(aHref, u"//"_ns)) { hostname = Substring(aHref, 2); } else { nsCOMPtr uri; @@ -1162,7 +1161,7 @@ void nsContentSink::StartLayout(bool aIgnorePendingSheets) { if (aIgnorePendingSheets) { nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Layout"), mDocument, + nsIScriptError::warningFlag, "Layout"_ns, mDocument, nsContentUtils::eLAYOUT_PROPERTIES, "ForcedLayoutStart"); } @@ -1559,9 +1558,9 @@ void nsContentSink::NotifyDocElementCreated(Document* aDoc) { observerService->NotifyObservers( ToSupports(aDoc), "document-element-inserted", EmptyString().get()); - nsContentUtils::DispatchChromeEvent( - aDoc, ToSupports(aDoc), NS_LITERAL_STRING("DOMDocElementInserted"), - CanBubble::eYes, Cancelable::eNo); + nsContentUtils::DispatchChromeEvent(aDoc, ToSupports(aDoc), + u"DOMDocElementInserted"_ns, + CanBubble::eYes, Cancelable::eNo); } NS_IMETHODIMP diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp index c3fdba1ac1db..f96c316f7965 100644 --- a/dom/base/nsContentUtils.cpp +++ b/dom/base/nsContentUtils.cpp @@ -675,8 +675,7 @@ nsresult nsContentUtils::Init() { #endif nsDependentCString buildID(mozilla::PlatformBuildID()); - sJSBytecodeMimeType = - new nsCString(NS_LITERAL_CSTRING("javascript/moz-bytecode-") + buildID); + sJSBytecodeMimeType = new nsCString("javascript/moz-bytecode-"_ns + buildID); Element::InitCCCallbacks(); @@ -1064,8 +1063,8 @@ nsContentUtils::InternalSerializeAutocompleteAttribute( enumValue.ParseEnumValue(tokenString, kAutocompleteFieldNameTable, false); if (result) { // Off/Automatic/Normal categories. - if (enumValue.Equals(NS_LITERAL_STRING("off"), eIgnoreCase) || - enumValue.Equals(NS_LITERAL_STRING("on"), eIgnoreCase)) { + if (enumValue.Equals(u"off"_ns, eIgnoreCase) || + enumValue.Equals(u"on"_ns, eIgnoreCase)) { if (numTokens > 1) { return eAutocompleteAttrState_Invalid; } @@ -1073,7 +1072,7 @@ nsContentUtils::InternalSerializeAutocompleteAttribute( ASCIIToLower(str); aInfo.mFieldName.Assign(str); aInfo.mCanAutomaticallyPersist = - !enumValue.Equals(NS_LITERAL_STRING("off"), eIgnoreCase); + !enumValue.Equals(u"off"_ns, eIgnoreCase); return eAutocompleteAttrState_Valid; } @@ -2709,9 +2708,9 @@ static inline void KeyAppendInt(int32_t aInt, nsACString& aKey) { static inline bool IsAutocompleteOff(const nsIContent* aContent) { return aContent->IsElement() && - aContent->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::autocomplete, - NS_LITERAL_STRING("off"), eIgnoreCase); + aContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::autocomplete, u"off"_ns, + eIgnoreCase); } /*static*/ @@ -2799,11 +2798,11 @@ void nsContentUtils::GenerateStateKey(nsIContent* aContent, Document* aDocument, MOZ_ASSERT(formElement->GetFormNumberForStateKey() != -1, "when generating a state key for a parser inserted form " "control we should have a parser inserted
element"); - KeyAppendString(NS_LITERAL_CSTRING("fp"), aKey); + KeyAppendString("fp"_ns, aKey); KeyAppendInt(formElement->GetFormNumberForStateKey(), aKey); appendedForm = true; } else { - KeyAppendString(NS_LITERAL_CSTRING("fn"), aKey); + KeyAppendString("fn"_ns, aKey); int32_t index = htmlForms->IndexOf(formElement, false); if (index <= -1) { // @@ -2840,12 +2839,12 @@ void nsContentUtils::GenerateStateKey(nsIContent* aContent, Document* aDocument, // inserted control, or the index of the control in the document // otherwise. if (parserInserted) { - KeyAppendString(NS_LITERAL_CSTRING("dp"), aKey); + KeyAppendString("dp"_ns, aKey); KeyAppendInt(control->GetParserInsertedControlNumberForStateKey(), aKey); generatedUniqueKey = true; } else { - KeyAppendString(NS_LITERAL_CSTRING("dn"), aKey); + KeyAppendString("dn"_ns, aKey); int32_t index = htmlFormControls->IndexOf(aContent, true); if (index > -1) { KeyAppendInt(index, aKey); @@ -2872,7 +2871,7 @@ void nsContentUtils::GenerateStateKey(nsIContent* aContent, Document* aDocument, } else { // Append a character that is not "d" or "f" to disambiguate from // the case when we were a form control in an HTML document. - KeyAppendString(NS_LITERAL_CSTRING("o"), aKey); + KeyAppendString("o"_ns, aKey); } // Now start at aContent and append the indices of it and all its ancestors @@ -3764,7 +3763,7 @@ nsresult nsContentUtils::ReportToConsole( /* static */ void nsContentUtils::ReportEmptyGetElementByIdArg(const Document* aDoc) { - ReportToConsole(nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), aDoc, + ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, aDoc, nsContentUtils::eDOM_PROPERTIES, "EmptyGetElementByIdParam"); } @@ -3934,7 +3933,7 @@ nsAtom* nsContentUtils::GetEventMessageAndAtom( } *aEventMessage = eUnidentifiedEvent; - RefPtr atom = NS_AtomizeMainThread(NS_LITERAL_STRING("on") + aName); + RefPtr atom = NS_AtomizeMainThread(u"on"_ns + aName); sUserDefinedEvents->AppendElement(atom); mapping.mAtom = atom; mapping.mMessage = eUnidentifiedEvent; @@ -3967,7 +3966,7 @@ EventMessage nsContentUtils::GetEventMessageAndAtomForListener( if (mapping.mMaybeSpecialSVGorSMILEvent) { // Try the atom version so that we should get the right message for // SVG/SMIL. - atom = NS_AtomizeMainThread(NS_LITERAL_STRING("on") + aName); + atom = NS_AtomizeMainThread(u"on"_ns + aName); msg = GetEventMessage(atom); } else { atom = mapping.mAtom; @@ -3995,7 +3994,7 @@ static nsresult GetEventAndTarget(Document* aDoc, nsISupports* aTarget, ErrorResult err; RefPtr event = - aDoc->CreateEvent(NS_LITERAL_STRING("Events"), CallerType::System, err); + aDoc->CreateEvent(u"Events"_ns, CallerType::System, err); if (NS_WARN_IF(err.Failed())) { return err.StealNSResult(); } @@ -4299,9 +4298,9 @@ void nsContentUtils::RequestFrameFocus(Element& aFrameElement, bool aCanRaise, RefPtr target = &aFrameElement; bool defaultAction = true; if (aCanRaise) { - DispatchEventOnlyToChrome( - target->OwnerDoc(), target, NS_LITERAL_STRING("framefocusrequested"), - CanBubble::eYes, Cancelable::eYes, &defaultAction); + DispatchEventOnlyToChrome(target->OwnerDoc(), target, + u"framefocusrequested"_ns, CanBubble::eYes, + Cancelable::eYes, &defaultAction); } if (!defaultAction) { return; @@ -4974,7 +4973,7 @@ nsresult nsContentUtils::ConvertToPlainText(const nsAString& aSourceBuffer, nsCOMPtr encoder = do_createDocumentEncoder("text/plain"); - rv = encoder->Init(document, NS_LITERAL_STRING("text/plain"), aFlags); + rv = encoder->Init(document, u"text/plain"_ns, aFlags); NS_ENSURE_SUCCESS(rv, rv); encoder->SetWrapColumn(aWrapCol); @@ -5938,7 +5937,7 @@ nsresult nsContentUtils::DispatchXULCommand(nsIContent* aTarget, bool aTrusted, RefPtr xulCommand = new XULCommandEvent(doc, presContext, nullptr); - xulCommand->InitCommandEvent(NS_LITERAL_STRING("command"), true, true, + xulCommand->InitCommandEvent(u"command"_ns, true, true, nsGlobalWindowInner::Cast(doc->GetInnerWindow()), 0, aCtrl, aAlt, aShift, aMeta, aSourceEvent, aInputSource, IgnoreErrors()); @@ -6323,7 +6322,7 @@ bool nsContentUtils::AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal) { return (StaticPrefs::dom_allow_XUL_XBL_for_file() && aPrincipal->SchemeIs("file")) || - IsSitePermAllow(aPrincipal, NS_LITERAL_CSTRING("allowXULXBL")); + IsSitePermAllow(aPrincipal, "allowXULXBL"_ns); } bool nsContentUtils::IsPDFJSEnabled() { @@ -6403,9 +6402,8 @@ static void ReportPatternCompileFailure(nsAString& aPattern, return; } - nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("DOM"), aDocument, - nsContentUtils::eDOM_PROPERTIES, + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "DOM"_ns, + aDocument, nsContentUtils::eDOM_PROPERTIES, "PatternAttributeCompileFailure", strings); savedExc.drop(); } @@ -6806,9 +6804,9 @@ bool nsContentUtils::IsForbiddenRequestHeader(const nsACString& aHeader) { return true; } - return StringBeginsWith(aHeader, NS_LITERAL_CSTRING("proxy-"), + return StringBeginsWith(aHeader, "proxy-"_ns, nsCaseInsensitiveCStringComparator) || - StringBeginsWith(aHeader, NS_LITERAL_CSTRING("sec-"), + StringBeginsWith(aHeader, "sec-"_ns, nsCaseInsensitiveCStringComparator); } @@ -7310,7 +7308,7 @@ bool nsContentUtils::IsFileImage(nsIFile* aFile, nsACString& aType) { return false; } - return StringBeginsWith(aType, NS_LITERAL_CSTRING("image/")); + return StringBeginsWith(aType, "image/"_ns); } nsresult nsContentUtils::CalculateBufferSizeForImage( @@ -7991,8 +7989,7 @@ ReferrerPolicy nsContentUtils::GetReferrerPolicyFromChannel( nsresult rv; nsAutoCString headerValue; - rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("referrer-policy"), - headerValue); + rv = httpChannel->GetResponseHeader("referrer-policy"_ns, headerValue); if (NS_FAILED(rv) || headerValue.IsEmpty()) { return ReferrerPolicy::_empty; } @@ -8537,8 +8534,8 @@ static void StartElement(Element* aContent, StringBuilder& aBuilder) { // Filter out any attribute starting with [-|_]moz nsDependentAtomString attrNameStr(attName); - if (StringBeginsWith(attrNameStr, NS_LITERAL_STRING("_moz")) || - StringBeginsWith(attrNameStr, NS_LITERAL_STRING("-moz"))) { + if (StringBeginsWith(attrNameStr, u"_moz"_ns) || + StringBeginsWith(attrNameStr, u"-moz"_ns)) { continue; } @@ -8549,7 +8546,7 @@ static void StartElement(Element* aContent, StringBuilder& aBuilder) { // Bug 16988. Yuck. if (localName == nsGkAtoms::br && tagNS == kNameSpaceID_XHTML && attName == nsGkAtoms::type && attNs == kNameSpaceID_None && - StringBeginsWith(*attValue, NS_LITERAL_STRING("_moz"))) { + StringBeginsWith(*attValue, u"_moz"_ns)) { delete attValue; continue; } @@ -9536,8 +9533,7 @@ bool nsContentUtils::ShouldBlockReservedKeys(WidgetKeyboardEvent* aKeyEvent) { } if (principal) { - return nsContentUtils::IsSitePermDeny(principal, - NS_LITERAL_CSTRING("shortcuts")); + return nsContentUtils::IsSitePermDeny(principal, "shortcuts"_ns); } return false; @@ -9744,11 +9740,9 @@ bool nsContentUtils::GetUserIsInteracting() { /* static */ bool nsContentUtils::GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult) { - nsresult rv = - aChannel->GetResponseHeader(NS_LITERAL_CSTRING("SourceMap"), aResult); + nsresult rv = aChannel->GetResponseHeader("SourceMap"_ns, aResult); if (NS_FAILED(rv)) { - rv = - aChannel->GetResponseHeader(NS_LITERAL_CSTRING("X-SourceMap"), aResult); + rv = aChannel->GetResponseHeader("X-SourceMap"_ns, aResult); } return NS_SUCCEEDED(rv); } @@ -9826,7 +9820,7 @@ void nsContentUtils::UserInteractionObserver::AnnotateHang( BackgroundHangAnnotations& aAnnotations) { // NOTE: Only annotate the hang report if the user is known to be interacting. if (sUserActive) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("UserInteracting"), true); + aAnnotations.AddAnnotation(u"UserInteracting"_ns, true); } } @@ -10167,8 +10161,7 @@ bool nsContentUtils::IsURIInList(nsIURI* aURI, const nsCString& aList) { if (startIndexOfNextLevel <= 0) { break; } - host = NS_LITERAL_CSTRING("*") + - nsDependentCSubstring(host, startIndexOfNextLevel); + host = "*"_ns + nsDependentCSubstring(host, startIndexOfNextLevel); } } diff --git a/dom/base/nsCopySupport.cpp b/dom/base/nsCopySupport.cpp index 4e61ccb56cd5..2d7a5e72edc1 100644 --- a/dom/base/nsCopySupport.cpp +++ b/dom/base/nsCopySupport.cpp @@ -918,7 +918,7 @@ bool nsCopySupport::FireClipboardEvent(EventMessage aEventMessage, // Now that we have copied, update the clipboard commands. This should have // the effect of updating the enabled state of the paste menu item. if (doDefault || count) { - piWindow->UpdateCommands(NS_LITERAL_STRING("clipboard"), nullptr, 0); + piWindow->UpdateCommands(u"clipboard"_ns, nullptr, 0); } if (aActionTaken) { diff --git a/dom/base/nsDOMDataChannel.cpp b/dom/base/nsDOMDataChannel.cpp index 51421b2e2ac3..77401ea1e052 100644 --- a/dom/base/nsDOMDataChannel.cpp +++ b/dom/base/nsDOMDataChannel.cpp @@ -312,7 +312,7 @@ nsresult nsDOMDataChannel::DoOnMessageAvailable(const nsACString& aData, RefPtr event = new MessageEvent(this, nullptr, nullptr); - event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), CanBubble::eNo, + event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo, Cancelable::eNo, jsData, mOrigin, EmptyString(), nullptr, Sequence>()); event->SetTrusted(true); @@ -364,7 +364,7 @@ nsresult nsDOMDataChannel::OnChannelConnected(nsISupports* aContext) { DC_DEBUG( ("%p(%p): %s - Dispatching\n", this, (void*)mDataChannel, __FUNCTION__)); - return OnSimpleEvent(aContext, NS_LITERAL_STRING("open")); + return OnSimpleEvent(aContext, u"open"_ns); } nsresult nsDOMDataChannel::OnChannelClosed(nsISupports* aContext) { @@ -377,7 +377,7 @@ nsresult nsDOMDataChannel::OnChannelClosed(nsISupports* aContext) { DC_DEBUG(("%p(%p): %s - Dispatching\n", this, (void*)mDataChannel, __FUNCTION__)); - rv = OnSimpleEvent(aContext, NS_LITERAL_STRING("close")); + rv = OnSimpleEvent(aContext, u"close"_ns); // no more events can happen mSentClose = true; } else { @@ -391,7 +391,7 @@ nsresult nsDOMDataChannel::OnBufferLow(nsISupports* aContext) { DC_DEBUG( ("%p(%p): %s - Dispatching\n", this, (void*)mDataChannel, __FUNCTION__)); - return OnSimpleEvent(aContext, NS_LITERAL_STRING("bufferedamountlow")); + return OnSimpleEvent(aContext, u"bufferedamountlow"_ns); } nsresult nsDOMDataChannel::NotBuffered(nsISupports* aContext) { diff --git a/dom/base/nsDOMSerializer.cpp b/dom/base/nsDOMSerializer.cpp index fdfb73986d31..8571c29f6cbb 100644 --- a/dom/base/nsDOMSerializer.cpp +++ b/dom/base/nsDOMSerializer.cpp @@ -33,7 +33,7 @@ static already_AddRefed SetUpEncoder( // This method will fail if no document nsresult rv = encoder->NativeInit( - doc, NS_LITERAL_STRING("application/xhtml+xml"), + doc, u"application/xhtml+xml"_ns, nsIDocumentEncoder::OutputRaw | nsIDocumentEncoder::OutputDontRewriteEncodingDeclaration); diff --git a/dom/base/nsFocusManager.cpp b/dom/base/nsFocusManager.cpp index 57014f641df7..03cfcf0aa688 100644 --- a/dom/base/nsFocusManager.cpp +++ b/dom/base/nsFocusManager.cpp @@ -93,7 +93,7 @@ LazyLogModule gFocusNavigationLog("FocusNavigation"); #define LOGTAG(log, format, content) \ if (MOZ_LOG_TEST(log, LogLevel::Debug)) { \ - nsAutoCString tag(NS_LITERAL_CSTRING("(none)")); \ + nsAutoCString tag("(none)"_ns); \ if (content) { \ content->NodeInfo()->NameAtom()->ToUTF8String(tag); \ } \ @@ -1026,7 +1026,7 @@ nsFocusManager::WindowHidden(mozIDOMWindowProxy* aWindow) { if (oldFocusedElement && oldFocusedElement->IsInComposedDoc()) { NotifyFocusStateChange(oldFocusedElement, nullptr, mFocusedWindow->ShouldShowFocusRing(), 0, false); - window->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + window->UpdateCommands(u"focus"_ns, nullptr, 0); if (presShell) { SendFocusOrBlurEvent(eBlur, presShell, @@ -1291,9 +1291,8 @@ void nsFocusManager::ActivateOrDeactivate(nsPIDOMWindowOuter* aWindow, if (aWindow->GetExtantDoc()) { nsContentUtils::DispatchEventOnlyToChrome( aWindow->GetExtantDoc(), aWindow->GetCurrentInnerWindow(), - aActive ? NS_LITERAL_STRING("activate") - : NS_LITERAL_STRING("deactivate"), - CanBubble::eYes, Cancelable::eYes, nullptr); + aActive ? u"activate"_ns : u"deactivate"_ns, CanBubble::eYes, + Cancelable::eYes, nullptr); } // Look for any remote child frames, iterate over them and send the activation @@ -1331,7 +1330,7 @@ void LogWarningFullscreenWindowRaise(Element* aElement) { NS_ENSURE_SUCCESS_VOID(rv); Unused << nsContentUtils::ReportToConsoleByWindowID( - localizedMsg, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), + localizedMsg, nsIScriptError::warningFlag, "DOM"_ns, windowGlobalParent->InnerWindowId(), windowGlobalParent->GetDocumentURI()); } @@ -1533,10 +1532,10 @@ void nsFocusManager::SetFocusInner(Element* aNewContent, int32_t aFlags, nsContentUtils::GetRootDocument(elementToFocus->OwnerDoc()) ->GetFullscreenElement() && nsContentUtils::HasPluginWithUncontrolledEventDispatch(elementToFocus)) { - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), - elementToFocus->OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, - "FocusedWindowedPluginWhileFullscreen"); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + elementToFocus->OwnerDoc(), + nsContentUtils::eDOM_PROPERTIES, + "FocusedWindowedPluginWhileFullscreen"); Document::AsyncExitFullscreen(elementToFocus->OwnerDoc()); } #endif @@ -1632,8 +1631,7 @@ void nsFocusManager::SetFocusInner(Element* aNewContent, int32_t aFlags, // update the commands even when inactive so that the attributes for that // window are up to date. - if (allowFrameSwitch) - newWindow->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + if (allowFrameSwitch) newWindow->UpdateCommands(u"focus"_ns, nullptr, 0); if (aFlags & FLAG_RAISE) { if (newRootBrowsingContext) { @@ -2188,7 +2186,7 @@ bool nsFocusManager::BlurImpl(BrowsingContext* aBrowsingContextToClear, // window, then this was a blur caused by the active window being lowered, // so there is no need to update the commands if (GetActiveBrowsingContext()) { - window->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + window->UpdateCommands(u"focus"_ns, nullptr, 0); } SendFocusOrBlurEvent(eBlur, presShell, element->GetComposedDoc(), element, @@ -2436,7 +2434,7 @@ void nsFocusManager::Focus(nsPIDOMWindowOuter* aWindow, Element* aElement, // commands // XXXndeakin P2 someone could adjust the focus during the update if (!aWindowRaised) { - aWindow->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + aWindow->UpdateCommands(u"focus"_ns, nullptr, 0); } if (!aFocusInOtherContentProcess) { @@ -2448,7 +2446,7 @@ void nsFocusManager::Focus(nsPIDOMWindowOuter* aWindow, Element* aElement, IMEStateManager::OnChangeFocus(presContext, nullptr, GetFocusMoveActionCause(aFlags)); if (!aWindowRaised) { - aWindow->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + aWindow->UpdateCommands(u"focus"_ns, nullptr, 0); } } } else { @@ -2477,8 +2475,7 @@ void nsFocusManager::Focus(nsPIDOMWindowOuter* aWindow, Element* aElement, GetFocusMoveActionCause(aFlags)); } - if (!aWindowRaised) - aWindow->UpdateCommands(NS_LITERAL_STRING("focus"), nullptr, 0); + if (!aWindowRaised) aWindow->UpdateCommands(u"focus"_ns, nullptr, 0); } // update the caret visibility and position to match the newly focused @@ -2819,9 +2816,8 @@ void nsFocusManager::UpdateCaret(bool aMoveCaretToFocus, bool aUpdateVisibility, if (!browseWithCaret) { nsCOMPtr docElement = mFocusedWindow->GetFrameElementInternal(); if (docElement) - browseWithCaret = - docElement->AttrValueIs(kNameSpaceID_None, nsGkAtoms::showcaret, - NS_LITERAL_STRING("true"), eCaseMatters); + browseWithCaret = docElement->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::showcaret, u"true"_ns, eCaseMatters); } SetCaretVisible(presShell, browseWithCaret, aContent); diff --git a/dom/base/nsFrameLoader.cpp b/dom/base/nsFrameLoader.cpp index 9115273ae33d..142080620890 100644 --- a/dom/base/nsFrameLoader.cpp +++ b/dom/base/nsFrameLoader.cpp @@ -508,8 +508,7 @@ void nsFrameLoader::LoadFrame(bool aOriginalSrc) { // If the URI was malformed, try to recover by loading about:blank. if (rv == NS_ERROR_MALFORMED_URI) { - rv = NS_NewURI(getter_AddRefs(uri), NS_LITERAL_STRING("about:blank"), - encoding, base_uri); + rv = NS_NewURI(getter_AddRefs(uri), u"about:blank"_ns, encoding, base_uri); } if (NS_SUCCEEDED(rv)) { @@ -538,8 +537,7 @@ void nsFrameLoader::FireErrorEvent() { } RefPtr loadBlockingAsyncDispatcher = new LoadBlockingAsyncEventDispatcher( - mOwnerContent, NS_LITERAL_STRING("error"), CanBubble::eNo, - ChromeOnlyDispatch::eNo); + mOwnerContent, u"error"_ns, CanBubble::eNo, ChromeOnlyDispatch::eNo); loadBlockingAsyncDispatcher->PostDOMEvent(); } @@ -994,11 +992,9 @@ bool nsFrameLoader::Show(nsSubDocumentFrame* frame) { // same editor object, instead of creating a new one. RefPtr htmlEditor = GetDocShell()->GetHTMLEditor(); Unused << htmlEditor; - htmlDoc->SetDesignMode(NS_LITERAL_STRING("off"), Nothing(), - IgnoreErrors()); + htmlDoc->SetDesignMode(u"off"_ns, Nothing(), IgnoreErrors()); - htmlDoc->SetDesignMode(NS_LITERAL_STRING("on"), Nothing(), - IgnoreErrors()); + htmlDoc->SetDesignMode(u"on"_ns, Nothing(), IgnoreErrors()); } else { // Re-initialize the presentation for contenteditable documents bool editable = false, hasEditingSession = false; @@ -3227,7 +3223,7 @@ void nsFrameLoader::InitializeBrowserAPI() { return; } mMessageManager->LoadFrameScript( - NS_LITERAL_STRING("chrome://global/content/BrowserElementChild.js"), + u"chrome://global/content/BrowserElementChild.js"_ns, /* allowDelayedLoad = */ true, /* aRunInGlobalScope */ true, IgnoreErrors()); @@ -3478,9 +3474,9 @@ void nsFrameLoader::MaybeNotifyCrashed(BrowsingContext* aBrowsingContext, // Fire the actual crashed event. nsString eventName; if (aChannel && !aChannel->DoBuildIDsMatch()) { - eventName = NS_LITERAL_STRING("oop-browser-buildid-mismatch"); + eventName = u"oop-browser-buildid-mismatch"_ns; } else { - eventName = NS_LITERAL_STRING("oop-browser-crashed"); + eventName = u"oop-browser-crashed"_ns; } FrameCrashedEventInit init; diff --git a/dom/base/nsFrameLoaderOwner.cpp b/dom/base/nsFrameLoaderOwner.cpp index f0292a629204..907bd78cde86 100644 --- a/dom/base/nsFrameLoaderOwner.cpp +++ b/dom/base/nsFrameLoaderOwner.cpp @@ -183,9 +183,9 @@ void nsFrameLoaderOwner::ChangeRemotenessCommon( // to what XULFrameElement does after rebinding to the tree. // ChromeOnlyDispatch is turns on to make sure this isn't fired into // content. - (new mozilla::AsyncEventDispatcher( - owner, NS_LITERAL_STRING("XULFrameLoaderCreated"), - mozilla::CanBubble::eYes, mozilla::ChromeOnlyDispatch::eYes)) + (new mozilla::AsyncEventDispatcher(owner, u"XULFrameLoaderCreated"_ns, + mozilla::CanBubble::eYes, + mozilla::ChromeOnlyDispatch::eYes)) ->RunDOMEventWhenSafe(); } } diff --git a/dom/base/nsFrameMessageManager.cpp b/dom/base/nsFrameMessageManager.cpp index b748c1435747..7673869803ba 100644 --- a/dom/base/nsFrameMessageManager.cpp +++ b/dom/base/nsFrameMessageManager.cpp @@ -391,12 +391,12 @@ bool nsFrameMessageManager::GetParamsForMessage(JSContext* aCx, nsJSUtils::GetCallingLocation(aCx, filename, &lineno, &column); nsCOMPtr error( do_CreateInstance(NS_SCRIPTERROR_CONTRACTID)); - error->Init(NS_LITERAL_STRING("Sending message that cannot be cloned. Are " - "you trying to send an XPCOM object?"), - filename, EmptyString(), lineno, column, - nsIScriptError::warningFlag, "chrome javascript", - false /* from private window */, - true /* from chrome context */); + error->Init( + u"Sending message that cannot be cloned. Are " + "you trying to send an XPCOM object?"_ns, + filename, EmptyString(), lineno, column, nsIScriptError::warningFlag, + "chrome javascript", false /* from private window */, + true /* from chrome context */); console->LogMessage(error); } @@ -742,9 +742,10 @@ void nsFrameMessageManager::ReceiveMessage( data->Write(cx, rval, aError); if (NS_WARN_IF(aError.Failed())) { aRetVal->RemoveLastElement(); - nsString msg = aMessage + NS_LITERAL_STRING( - ": message reply cannot be cloned. Are " - "you trying to send an XPCOM object?"); + nsString msg = + aMessage + nsLiteralString( + u": message reply cannot be cloned. Are " + "you trying to send an XPCOM object?"); nsCOMPtr console( do_GetService(NS_CONSOLESERVICE_CONTRACTID)); diff --git a/dom/base/nsGlobalWindowInner.cpp b/dom/base/nsGlobalWindowInner.cpp index 465acf855c00..4d49899cafad 100644 --- a/dom/base/nsGlobalWindowInner.cpp +++ b/dom/base/nsGlobalWindowInner.cpp @@ -2936,7 +2936,7 @@ void nsGlobalWindowInner::GetOwnPropertyNames( } // "Components" is marked as enumerable but only resolved on demand :-/. - // aNames.AppendElement(NS_LITERAL_STRING("Components")); + // aNames.AppendElement(u"Components"_ns); JS::Rooted wrapper(aCx, GetWrapper()); @@ -4261,7 +4261,7 @@ nsresult nsGlobalWindowInner::FireHashchange(const nsAString& aOldURL, init.mOldURL = aOldURL; RefPtr event = - HashChangeEvent::Constructor(this, NS_LITERAL_STRING("hashchange"), init); + HashChangeEvent::Constructor(this, u"hashchange"_ns, init); event->SetTrusted(true); @@ -4299,7 +4299,7 @@ nsresult nsGlobalWindowInner::DispatchSyncPopState() { init.mState = stateJSValue; RefPtr event = - PopStateEvent::Constructor(this, NS_LITERAL_STRING("popstate"), init); + PopStateEvent::Constructor(this, u"popstate"_ns, init); event->SetTrusted(true); event->SetTarget(this); @@ -4755,7 +4755,7 @@ nsGlobalWindowInner::ShowSlowScriptDialog(JSContext* aCx, mHasHadSlowScript = true; // Override the cursor to something that we're sure the user can see. - SetCursor(NS_LITERAL_CSTRING("auto"), IgnoreErrors()); + SetCursor("auto"_ns, IgnoreErrors()); if (XRE_IsContentProcess() && ProcessHangMonitor::Get()) { ProcessHangMonitor::SlowScriptAction action; @@ -4982,7 +4982,7 @@ nsresult nsGlobalWindowInner::Observe(nsISupports* aSubject, const char* aTopic, nsAutoCString type; perm->GetType(type); - if (type == NS_LITERAL_CSTRING("autoplay-media")) { + if (type == "autoplay-media"_ns) { UpdateAutoplayPermission(); } @@ -5017,7 +5017,7 @@ nsresult nsGlobalWindowInner::Observe(nsISupports* aSubject, const char* aTopic, } RefPtr event = NS_NewDOMEvent(this, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("languagechange"), false, false); + event->InitEvent(u"languagechange"_ns, false, false); event->SetTrusted(true); ErrorResult rv; @@ -6433,8 +6433,8 @@ void nsGlobalWindowInner::DispatchVRDisplayActivate( init.mDisplay = display; init.mReason.Construct(aReason); - RefPtr event = VRDisplayEvent::Constructor( - this, NS_LITERAL_STRING("vrdisplayactivate"), init); + RefPtr event = + VRDisplayEvent::Constructor(this, u"vrdisplayactivate"_ns, init); // vrdisplayactivate is a trusted event, allowing VRDisplay.requestPresent // to be used in response to link traversal, user request (chrome UX), and // HMD mounting detection sensors. @@ -6470,8 +6470,8 @@ void nsGlobalWindowInner::DispatchVRDisplayDeactivate( init.mDisplay = display; init.mReason.Construct(aReason); - RefPtr event = VRDisplayEvent::Constructor( - this, NS_LITERAL_STRING("vrdisplaydeactivate"), init); + RefPtr event = + VRDisplayEvent::Constructor(this, u"vrdisplaydeactivate"_ns, init); event->SetTrusted(true); DispatchEvent(*event); // Once we dispatch the event, we must not access any members as an event @@ -6496,8 +6496,8 @@ void nsGlobalWindowInner::DispatchVRDisplayConnect(uint32_t aDisplayID) { init.mDisplay = display; // VRDisplayEvent.reason is not set for vrdisplayconnect - RefPtr event = VRDisplayEvent::Constructor( - this, NS_LITERAL_STRING("vrdisplayconnect"), init); + RefPtr event = + VRDisplayEvent::Constructor(this, u"vrdisplayconnect"_ns, init); event->SetTrusted(true); DispatchEvent(*event); // Once we dispatch the event, we must not access any members as an event @@ -6522,8 +6522,8 @@ void nsGlobalWindowInner::DispatchVRDisplayDisconnect(uint32_t aDisplayID) { init.mDisplay = display; // VRDisplayEvent.reason is not set for vrdisplaydisconnect - RefPtr event = VRDisplayEvent::Constructor( - this, NS_LITERAL_STRING("vrdisplaydisconnect"), init); + RefPtr event = + VRDisplayEvent::Constructor(this, u"vrdisplaydisconnect"_ns, init); event->SetTrusted(true); DispatchEvent(*event); // Once we dispatch the event, we must not access any members as an event @@ -6547,8 +6547,8 @@ void nsGlobalWindowInner::DispatchVRDisplayPresentChange(uint32_t aDisplayID) { init.mCancelable = false; init.mDisplay = display; // VRDisplayEvent.reason is not set for vrdisplaypresentchange - RefPtr event = VRDisplayEvent::Constructor( - this, NS_LITERAL_STRING("vrdisplaypresentchange"), init); + RefPtr event = + VRDisplayEvent::Constructor(this, u"vrdisplaypresentchange"_ns, init); event->SetTrusted(true); DispatchEvent(*event); // Once we dispatch the event, we must not access any members as an event @@ -6942,8 +6942,7 @@ void nsGlobalWindowInner::GetSidebar(OwningExternalOrWindowProxy& aResult, ErrorResult& aRv) { #ifdef HAVE_SIDEBAR // First check for a named frame named "sidebar" - RefPtr domWindow = - GetChildWindow(NS_LITERAL_STRING("sidebar")); + RefPtr domWindow = GetChildWindow(u"sidebar"_ns); if (domWindow) { aResult.SetAsWindowProxy() = std::move(domWindow); return; diff --git a/dom/base/nsGlobalWindowOuter.cpp b/dom/base/nsGlobalWindowOuter.cpp index 4a9ac122f0fd..23240e1baa4c 100644 --- a/dom/base/nsGlobalWindowOuter.cpp +++ b/dom/base/nsGlobalWindowOuter.cpp @@ -615,7 +615,7 @@ bool nsOuterWindowProxy::getOwnPropertyDescriptor( // case. if (!isSameOrigin && IsArrayIndex(GetArrayIndexFromId(id))) { // Step 2.5.2. - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("access")); + return ReportCrossOriginDenial(cx, id, "access"_ns); } // Step 2.5.1 is handled via the forwarding to js::Wrapper; it saves us an @@ -835,7 +835,7 @@ bool nsOuterWindowProxy::delete_(JSContext* cx, JS::Handle proxy, JS::Handle id, JS::ObjectOpResult& result) const { if (!IsPlatformObjectSameOrigin(cx, proxy)) { - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("delete")); + return ReportCrossOriginDenial(cx, id, "delete"_ns); } if (!GetSubframeWindow(cx, proxy, id).IsNull()) { @@ -1259,7 +1259,7 @@ already_AddRefed nsOuterWindowProxy::GetNoPDFJSPrincipal( } nsCOMPtr principal; - propBag->GetPropertyAsInterface(NS_LITERAL_STRING("noPDFJSPrincipal"), + propBag->GetPropertyAsInterface(u"noPDFJSPrincipal"_ns, NS_GET_IID(nsIPrincipal), getter_AddRefs(principal)); return principal.forget(); @@ -2592,8 +2592,8 @@ void nsGlobalWindowOuter::DispatchDOMWindowCreated() { // Fire DOMWindowCreated at chrome event listeners nsContentUtils::DispatchChromeEvent(mDoc, ToSupports(mDoc), - NS_LITERAL_STRING("DOMWindowCreated"), - CanBubble::eYes, Cancelable::eNo); + u"DOMWindowCreated"_ns, CanBubble::eYes, + Cancelable::eNo); nsCOMPtr observerService = mozilla::services::GetObserverService(); @@ -3342,7 +3342,7 @@ void nsGlobalWindowOuter::GetContentOuter(JSContext* aCx, already_AddRefed nsGlobalWindowOuter::GetContentInternal( ErrorResult& aError, CallerType aCallerType) { // First check for a named frame named "content" - RefPtr bc = GetChildWindow(NS_LITERAL_STRING("content")); + RefPtr bc = GetChildWindow(u"content"_ns); if (bc) { nsCOMPtr content(bc->GetDOMWindow()); return content.forget(); @@ -3919,7 +3919,7 @@ double nsGlobalWindowOuter::GetDevicePixelRatioOuter(CallerType aCallerType) { // blurriness... nsAutoCString origin; nsresult rv = this->GetPrincipal()->GetOrigin(origin); - if (NS_FAILED(rv) || origin != NS_LITERAL_CSTRING("resource://pdf.js")) { + if (NS_FAILED(rv) || origin != "resource://pdf.js"_ns) { return 1.0; } } @@ -4213,8 +4213,8 @@ bool nsGlobalWindowOuter::DispatchCustomEvent( bool nsGlobalWindowOuter::DispatchResizeEvent(const CSSIntSize& aSize) { ErrorResult res; - RefPtr domEvent = mDoc->CreateEvent(NS_LITERAL_STRING("CustomEvent"), - CallerType::System, res); + RefPtr domEvent = + mDoc->CreateEvent(u"CustomEvent"_ns, CallerType::System, res); if (res.Failed()) { return false; } @@ -4235,7 +4235,7 @@ bool nsGlobalWindowOuter::DispatchResizeEvent(const CSSIntSize& aSize) { } CustomEvent* customEvent = static_cast(domEvent.get()); - customEvent->InitCustomEvent(cx, NS_LITERAL_STRING("DOMWindowResize"), + customEvent->InitCustomEvent(cx, u"DOMWindowResize"_ns, /* aCanBubble = */ true, /* aCancelable = */ true, detailValue); @@ -4694,11 +4694,9 @@ bool nsGlobalWindowOuter::SetWidgetFullscreen(FullscreenReason aReason, /* virtual */ void nsGlobalWindowOuter::FullscreenWillChange(bool aIsFullscreen) { if (aIsFullscreen) { - DispatchCustomEvent(NS_LITERAL_STRING("willenterfullscreen"), - ChromeOnlyDispatch::eYes); + DispatchCustomEvent(u"willenterfullscreen"_ns, ChromeOnlyDispatch::eYes); } else { - DispatchCustomEvent(NS_LITERAL_STRING("willexitfullscreen"), - ChromeOnlyDispatch::eYes); + DispatchCustomEvent(u"willexitfullscreen"_ns, ChromeOnlyDispatch::eYes); } } @@ -4733,8 +4731,7 @@ void nsGlobalWindowOuter::FinishFullscreenChange(bool aIsFullscreen) { // dispatch a "fullscreen" DOM event so that XUL apps can // respond visually if we are kicked into full screen mode - DispatchCustomEvent(NS_LITERAL_STRING("fullscreen"), - ChromeOnlyDispatch::eYes); + DispatchCustomEvent(u"fullscreen"_ns, ChromeOnlyDispatch::eYes); if (!NS_WARN_IF(!IsChromeWindow())) { if (RefPtr presShell = @@ -4755,7 +4752,7 @@ void nsGlobalWindowOuter::FinishFullscreenChange(bool aIsFullscreen) { // XXXkhuey using the inner here, do we need to do something if it changes? ErrorResult rv; - mWakeLock = pmService->NewWakeLock(NS_LITERAL_STRING("DOM_Fullscreen"), + mWakeLock = pmService->NewWakeLock(u"DOM_Fullscreen"_ns, GetCurrentInnerWindow(), rv); NS_WARNING_ASSERTION(!rv.Failed(), "Failed to lock the wakelock"); rv.SuppressException(); @@ -4953,7 +4950,7 @@ bool nsGlobalWindowOuter::AlertOrConfirm(bool aAlert, const nsAString& aMessage, // Always allow content modal prompts for alert and confirm. if (nsCOMPtr promptBag = do_QueryInterface(prompt)) { - promptBag->SetPropertyAsUint32(NS_LITERAL_STRING("modalType"), + promptBag->SetPropertyAsUint32(u"modalType"_ns, nsIPrompt::MODAL_TYPE_CONTENT); } @@ -5043,7 +5040,7 @@ void nsGlobalWindowOuter::PromptOuter(const nsAString& aMessage, // Always allow content modal prompts for prompt. if (nsCOMPtr promptBag = do_QueryInterface(prompt)) { - promptBag->SetPropertyAsUint32(NS_LITERAL_STRING("modalType"), + promptBag->SetPropertyAsUint32(u"modalType"_ns, nsIPrompt::MODAL_TYPE_CONTENT); } @@ -5539,8 +5536,8 @@ void nsGlobalWindowOuter::FirePopupBlockedEvent( init.mPopupWindowName = aPopupWindowName; init.mPopupWindowFeatures = aPopupWindowFeatures; - RefPtr event = PopupBlockedEvent::Constructor( - aDoc, NS_LITERAL_STRING("DOMPopupBlocked"), init); + RefPtr event = + PopupBlockedEvent::Constructor(aDoc, u"DOMPopupBlocked"_ns, init); event->SetTrusted(true); @@ -6106,9 +6103,8 @@ void nsGlobalWindowOuter::CloseOuter(bool aTrustedCaller) { nsresult rv = mDoc->GetURL(url); NS_ENSURE_SUCCESS_VOID(rv); - if (!StringBeginsWith(url, NS_LITERAL_STRING("about:neterror")) && - !HadOriginalOpener() && !aTrustedCaller && - !IsOnlyTopLevelDocumentInSHistory()) { + if (!StringBeginsWith(url, u"about:neterror"_ns) && !HadOriginalOpener() && + !aTrustedCaller && !IsOnlyTopLevelDocumentInSHistory()) { bool allowClose = mAllowScriptsToClose || Preferences::GetBool("dom.allow_scripts_to_close_windows", true); @@ -6116,7 +6112,7 @@ void nsGlobalWindowOuter::CloseOuter(bool aTrustedCaller) { // We're blocking the close operation // report localized error msg in JS console nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Window"), + nsIScriptError::warningFlag, "DOM Window"_ns, mDoc, // Better name for the category? nsContentUtils::eDOM_PROPERTIES, "WindowCloseBlockedWarning"); @@ -6139,8 +6135,7 @@ void nsGlobalWindowOuter::CloseOuter(bool aTrustedCaller) { bool wasInClose = mInClose; mInClose = true; - if (!DispatchCustomEvent(NS_LITERAL_STRING("DOMWindowClose"), - ChromeOnlyDispatch::eYes)) { + if (!DispatchCustomEvent(u"DOMWindowClose"_ns, ChromeOnlyDispatch::eYes)) { // Someone chose to prevent the default action for this event, if // so, let's not close this window after all... @@ -6189,8 +6184,7 @@ void nsGlobalWindowOuter::ForceClose() { mInClose = true; - DispatchCustomEvent(NS_LITERAL_STRING("DOMWindowClose"), - ChromeOnlyDispatch::eYes); + DispatchCustomEvent(u"DOMWindowClose"_ns, ChromeOnlyDispatch::eYes); FinalClose(); } @@ -6376,7 +6370,7 @@ void nsGlobalWindowOuter::LeaveModalState() { if (topWin->mModalStateDepth == 0) { RefPtr event = NS_NewDOMEvent(inner, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("endmodalstate"), true, false); + event->InitEvent(u"endmodalstate"_ns, true, false); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; topWin->DispatchEvent(*event); @@ -7020,7 +7014,7 @@ nsresult nsGlobalWindowOuter::OpenInternal( OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP) && !mBrowsingContext->SameOriginWithTop()) { forceNoOpener = true; - windowName = NS_LITERAL_STRING("_blank"); + windowName = u"_blank"_ns; } bool windowExists = WindowExists(windowName, forceNoOpener, !aCalledNoScript); diff --git a/dom/base/nsHTMLContentSerializer.cpp b/dom/base/nsHTMLContentSerializer.cpp index 7b905bb20c87..4d5f2634b16e 100644 --- a/dom/base/nsHTMLContentSerializer.cpp +++ b/dom/base/nsHTMLContentSerializer.cpp @@ -66,8 +66,8 @@ bool nsHTMLContentSerializer::SerializeHTMLAttributes( // Filter out any attribute starting with [-|_]moz nsDependentAtomString attrNameStr(attrName); - if (StringBeginsWith(attrNameStr, NS_LITERAL_STRING("_moz")) || - StringBeginsWith(attrNameStr, NS_LITERAL_STRING("-moz"))) { + if (StringBeginsWith(attrNameStr, u"_moz"_ns) || + StringBeginsWith(attrNameStr, u"-moz"_ns)) { continue; } aElement->GetAttr(namespaceID, attrName, valueStr); @@ -107,8 +107,7 @@ bool nsHTMLContentSerializer::SerializeHTMLAttributes( nsAutoString header; aElement->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, header); if (header.LowerCaseEqualsLiteral("content-type")) { - valueStr = NS_LITERAL_STRING("text/html; charset=") + - NS_ConvertASCIItoUTF16(mCharset); + valueStr = u"text/html; charset="_ns + NS_ConvertASCIItoUTF16(mCharset); } } diff --git a/dom/base/nsINode.cpp b/dom/base/nsINode.cpp index 82268c5c51e7..38c7feadc485 100644 --- a/dom/base/nsINode.cpp +++ b/dom/base/nsINode.cpp @@ -694,14 +694,13 @@ std::ostream& operator<<(std::ostream& aStream, const nsINode& aNode) { } if (!elemDesc.IsEmpty()) { - elemDesc = elemDesc + NS_LITERAL_STRING("."); + elemDesc = elemDesc + u"."_ns; } elemDesc = elemDesc + localName; if (!id.IsEmpty()) { - elemDesc = - elemDesc + NS_LITERAL_STRING("['") + id + NS_LITERAL_STRING("']"); + elemDesc = elemDesc + u"['"_ns + id + u"']"_ns; } curr = curr->GetParentNode(); @@ -2833,9 +2832,8 @@ const RawServoSelectorList* nsINode::ParseSelectorList( if (list) { if (!*list) { // Invalid selector. - aRv.ThrowSyntaxError(NS_LITERAL_CSTRING("'") + - NS_ConvertUTF16toUTF8(aSelectorString) + - NS_LITERAL_CSTRING("' is not a valid selector")); + aRv.ThrowSyntaxError("'"_ns + NS_ConvertUTF16toUTF8(aSelectorString) + + "' is not a valid selector"_ns); return nullptr; } @@ -2853,8 +2851,8 @@ const RawServoSelectorList* nsINode::ParseSelectorList( // Now make sure we throw an exception if the selector was invalid. if (!ret) { - aRv.ThrowSyntaxError(NS_LITERAL_CSTRING("'") + selectorString + - NS_LITERAL_CSTRING("' is not a valid selector")); + aRv.ThrowSyntaxError("'"_ns + selectorString + + "' is not a valid selector"_ns); } return ret; diff --git a/dom/base/nsImageLoadingContent.cpp b/dom/base/nsImageLoadingContent.cpp index 73731c4dee5b..a24a30399cb1 100644 --- a/dom/base/nsImageLoadingContent.cpp +++ b/dom/base/nsImageLoadingContent.cpp @@ -255,16 +255,16 @@ void nsImageLoadingContent::OnLoadComplete(imgIRequest* aRequest, // Fire the appropriate DOM event. if (NS_SUCCEEDED(aStatus)) { - FireEvent(NS_LITERAL_STRING("load")); + FireEvent(u"load"_ns); // Do not fire loadend event for multipart/x-mixed-replace image streams. bool isMultipart; if (NS_FAILED(aRequest->GetMultipart(&isMultipart)) || !isMultipart) { - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"loadend"_ns); } } else { - FireEvent(NS_LITERAL_STRING("error")); - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"error"_ns); + FireEvent(u"loadend"_ns); } nsCOMPtr thisNode = @@ -991,8 +991,8 @@ nsImageLoadingContent::LoadImageWithChannel(nsIChannel* aChannel, // know what we tried (and failed) to load. if (!mCurrentRequest) aChannel->GetURI(getter_AddRefs(mCurrentURI)); - FireEvent(NS_LITERAL_STRING("error")); - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"error"_ns); + FireEvent(u"loadend"_ns); return rv; } @@ -1042,12 +1042,12 @@ nsresult nsImageLoadingContent::LoadImage(const nsAString& aNewURI, bool aForce, CancelImageRequests(aNotify); // Mark error event as cancelable only for src="" case, since only this // error causes site compat problem (bug 1308069) for now. - FireEvent(NS_LITERAL_STRING("error"), true); + FireEvent(u"error"_ns, true); return NS_OK; } // Fire loadstart event - FireEvent(NS_LITERAL_STRING("loadstart")); + FireEvent(u"loadstart"_ns); // Parse the URI string to get image URI nsCOMPtr imageURI; @@ -1077,14 +1077,14 @@ nsresult nsImageLoadingContent::LoadImage(nsIURI* aNewURI, bool aForce, // Fire loadstart event if required if (aLoadStart) { - FireEvent(NS_LITERAL_STRING("loadstart")); + FireEvent(u"loadstart"_ns); } if (!mLoadingEnabled) { // XXX Why fire an error here? seems like the callers to SetLoadingEnabled // don't want/need it. - FireEvent(NS_LITERAL_STRING("error")); - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"error"_ns); + FireEvent(u"loadend"_ns); return NS_OK; } @@ -1111,8 +1111,8 @@ nsresult nsImageLoadingContent::LoadImage(nsIURI* aNewURI, bool aForce, SetBlockedRequest(nsIContentPolicy::REJECT_REQUEST); - FireEvent(NS_LITERAL_STRING("error")); - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"error"_ns); + FireEvent(u"loadend"_ns); return NS_OK; } @@ -1209,8 +1209,8 @@ nsresult nsImageLoadingContent::LoadImage(nsIURI* aNewURI, bool aForce, // know what we tried (and failed) to load. if (!mCurrentRequest) mCurrentURI = aNewURI; - FireEvent(NS_LITERAL_STRING("error")); - FireEvent(NS_LITERAL_STRING("loadend")); + FireEvent(u"error"_ns); + FireEvent(u"loadend"_ns); } return NS_OK; diff --git a/dom/base/nsJSEnvironment.cpp b/dom/base/nsJSEnvironment.cpp index 492ce8bf3ab3..2c54b5aa8f4c 100644 --- a/dom/base/nsJSEnvironment.cpp +++ b/dom/base/nsJSEnvironment.cpp @@ -466,9 +466,8 @@ bool NS_HandleScriptError(nsIScriptGlobalObject* aScriptGlobal, if (errorDepth < 2) { // Dispatch() must be synchronous for the recursion block // (errorDepth) to work. - RefPtr event = - ErrorEvent::Constructor(nsGlobalWindowInner::Cast(win), - NS_LITERAL_STRING("error"), aErrorEventInit); + RefPtr event = ErrorEvent::Constructor( + nsGlobalWindowInner::Cast(win), u"error"_ns, aErrorEventInit); event->SetTrusted(true); EventDispatcher::DispatchDOMEvent(win, nullptr, event, presContext, @@ -524,7 +523,7 @@ class ScriptErrorEvent : public Runnable { } RefPtr event = ErrorEvent::Constructor( - nsGlobalWindowInner::Cast(win), NS_LITERAL_STRING("error"), init); + nsGlobalWindowInner::Cast(win), u"error"_ns, init); event->SetTrusted(true); EventDispatcher::DispatchDOMEvent(win, nullptr, event, presContext, diff --git a/dom/base/nsObjectLoadingContent.cpp b/dom/base/nsObjectLoadingContent.cpp index 1d98aa961cba..97abad22f62f 100644 --- a/dom/base/nsObjectLoadingContent.cpp +++ b/dom/base/nsObjectLoadingContent.cpp @@ -345,8 +345,8 @@ nsPluginCrashedEvent::Run() { init.mBubbles = true; init.mCancelable = true; - RefPtr event = PluginCrashedEvent::Constructor( - doc, NS_LITERAL_STRING("PluginCrashed"), init); + RefPtr event = + PluginCrashedEvent::Constructor(doc, u"PluginCrashed"_ns, init); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; @@ -601,7 +601,7 @@ void nsObjectLoadingContent::UnbindFromTree(bool aNullParent) { Document* doc = thisElement->GetComposedDoc(); if (doc && doc->IsActive()) { nsCOMPtr ev = - new nsSimplePluginEvent(doc, NS_LITERAL_STRING("PluginRemoved")); + new nsSimplePluginEvent(doc, u"PluginRemoved"_ns); NS_DispatchToCurrentThread(ev); } } @@ -763,8 +763,8 @@ nsresult nsObjectLoadingContent::InstantiatePluginInstance(bool aIsLoading) { // Fire plugin outdated event if necessary LOG(("OBJLC [%p]: Dispatching plugin outdated event for content\n", this)); - nsCOMPtr ev = new nsSimplePluginEvent( - thisContent, NS_LITERAL_STRING("PluginOutdated")); + nsCOMPtr ev = + new nsSimplePluginEvent(thisContent, u"PluginOutdated"_ns); nsresult rv = NS_DispatchToCurrentThread(ev); if (NS_FAILED(rv)) { NS_WARNING("failed to dispatch nsSimplePluginEvent"); @@ -783,8 +783,8 @@ nsresult nsObjectLoadingContent::InstantiatePluginInstance(bool aIsLoading) { } } - nsCOMPtr ev = new nsSimplePluginEvent( - thisContent, doc, NS_LITERAL_STRING("PluginInstantiated")); + nsCOMPtr ev = + new nsSimplePluginEvent(thisContent, doc, u"PluginInstantiated"_ns); NS_DispatchToCurrentThread(ev); #ifdef XP_MACOSX @@ -812,8 +812,7 @@ void nsObjectLoadingContent::GetNestedParams( nsCOMPtr allParams; NS_NAMED_LITERAL_STRING(xhtml_ns, "http://www.w3.org/1999/xhtml"); ErrorResult rv; - allParams = ourElement->GetElementsByTagNameNS( - xhtml_ns, NS_LITERAL_STRING("param"), rv); + allParams = ourElement->GetElementsByTagNameNS(xhtml_ns, u"param"_ns, rv); if (rv.Failed()) { return; } @@ -885,7 +884,7 @@ nsresult nsObjectLoadingContent::BuildParametersArray() { if (!wmodeOverride.IsEmpty()) { MozPluginParameter param; - param.mName = NS_LITERAL_STRING("wmode"); + param.mName = u"wmode"_ns; CopyASCIItoUTF16(wmodeOverride, param.mValue); mCachedAttributes.AppendElement(param); } @@ -901,7 +900,7 @@ nsresult nsObjectLoadingContent::BuildParametersArray() { MozPluginParameter param; element->GetAttr(kNameSpaceID_None, nsGkAtoms::data, param.mValue); if (!param.mValue.IsEmpty()) { - param.mName = NS_LITERAL_STRING("SRC"); + param.mName = u"SRC"_ns; mCachedAttributes.AppendElement(param); } } @@ -977,10 +976,10 @@ nsObjectLoadingContent::OnStartRequest(nsIRequest* aRequest) { nsCOMPtr uri; chan->GetURI(getter_AddRefs(uri)); nsString message = - NS_LITERAL_STRING("Blocking ") + + u"Blocking "_ns + NS_ConvertASCIItoUTF16(uri->GetSpecOrDefault().get()) + - NS_LITERAL_STRING( - " since it was found on an internal Firefox blocklist."); + nsLiteralString( + u" since it was found on an internal Firefox blocklist."); console->LogStringMessage(message.get()); } mContentBlockingEnabled = true; @@ -1283,7 +1282,7 @@ void nsObjectLoadingContent::MaybeRewriteYoutubeEmbed(nsIURI* aURI, // touch object nodes with "/embed/" urls that already do that right thing. nsAutoCString path; aURI->GetPathQueryRef(path); - if (!StringBeginsWith(path, NS_LITERAL_CSTRING("/v/"))) { + if (!StringBeginsWith(path, "/v/"_ns)) { return; } @@ -1325,8 +1324,7 @@ void nsObjectLoadingContent::MaybeRewriteYoutubeEmbed(nsIURI* aURI, } // Switch out video access url formats, which should possibly allow HTML5 // video loading. - uri.ReplaceSubstring(NS_LITERAL_CSTRING("/v/"), - NS_LITERAL_CSTRING("/embed/")); + uri.ReplaceSubstring("/v/"_ns, "/embed/"_ns); nsAutoString utf16URI = NS_ConvertUTF8toUTF16(uri); rv = nsContentUtils::NewURIWithDocumentCharset( aOutURI, utf16URI, thisContent->OwnerDoc(), aBaseURI); @@ -1343,9 +1341,8 @@ void nsObjectLoadingContent::MaybeRewriteYoutubeEmbed(nsIURI* aURI, msgName = "RewriteYouTubeEmbedPathParams"; } nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Plugins"), - thisContent->OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, msgName, - params); + nsIScriptError::warningFlag, "Plugins"_ns, thisContent->OwnerDoc(), + nsContentUtils::eDOM_PROPERTIES, msgName, params); } bool nsObjectLoadingContent::CheckLoadPolicy(int16_t* aContentPolicy) { @@ -1541,7 +1538,7 @@ nsObjectLoadingContent::UpdateObjectParameters() { if (rewrittenURI) { newURI = rewrittenURI; mRewrittenYoutubeEmbed = true; - newMime = NS_LITERAL_CSTRING("text/html"); + newMime = "text/html"_ns; } if (NS_FAILED(rv)) { @@ -2631,8 +2628,8 @@ nsNPAPIPluginInstance* nsObjectLoadingContent::ScriptRequestPluginInstance( // types, see header. if (callerIsContentJS && !mScriptRequested && InActiveDocument(thisContent) && mType == eType_Null && mFallbackType >= eFallbackClickToPlay) { - nsCOMPtr ev = new nsSimplePluginEvent( - thisContent, NS_LITERAL_STRING("PluginScripted")); + nsCOMPtr ev = + new nsSimplePluginEvent(thisContent, u"PluginScripted"_ns); nsresult rv = NS_DispatchToCurrentThread(ev); if (NS_FAILED(rv)) { MOZ_ASSERT_UNREACHABLE("failed to dispatch PluginScripted event"); @@ -3192,7 +3189,7 @@ bool nsObjectLoadingContent::HasGoodFallback() { nsresult rv = href->GetAsciiHost(asciiHost); if (NS_SUCCEEDED(rv) && !asciiHost.IsEmpty() && (asciiHost.EqualsLiteral("adobe.com") || - StringEndsWith(asciiHost, NS_LITERAL_CSTRING(".adobe.com")))) { + StringEndsWith(asciiHost, ".adobe.com"_ns))) { return false; } } @@ -3208,12 +3205,10 @@ bool nsObjectLoadingContent::HasGoodFallback() { ErrorResult rv; thisContent->GetTextContent(textContent, rv); bool hasText = - !rv.Failed() && (CaseInsensitiveFindInReadable( - NS_LITERAL_STRING("Flash"), textContent) || - CaseInsensitiveFindInReadable( - NS_LITERAL_STRING("Install"), textContent) || - CaseInsensitiveFindInReadable( - NS_LITERAL_STRING("Download"), textContent)); + !rv.Failed() && + (CaseInsensitiveFindInReadable(u"Flash"_ns, textContent) || + CaseInsensitiveFindInReadable(u"Install"_ns, textContent) || + CaseInsensitiveFindInReadable(u"Download"_ns, textContent)); if (hasText) { return false; @@ -3471,8 +3466,7 @@ void nsObjectLoadingContent::MaybeFireErrorEvent() { if (thisContent->IsHTMLElement(nsGkAtoms::object)) { RefPtr loadBlockingAsyncDispatcher = new LoadBlockingAsyncEventDispatcher( - thisContent, NS_LITERAL_STRING("error"), CanBubble::eNo, - ChromeOnlyDispatch::eNo); + thisContent, u"error"_ns, CanBubble::eNo, ChromeOnlyDispatch::eNo); loadBlockingAsyncDispatcher->PostDOMEvent(); } } diff --git a/dom/base/nsPlainTextSerializer.cpp b/dom/base/nsPlainTextSerializer.cpp index 7751846f1930..7e012317db85 100644 --- a/dom/base/nsPlainTextSerializer.cpp +++ b/dom/base/nsPlainTextSerializer.cpp @@ -236,7 +236,7 @@ uint32_t nsPlainTextSerializer::OutputManager::GetOutputLength() const { nsPlainTextSerializer::nsPlainTextSerializer() : mFloatingLines(-1), mLineBreakDue(false), - kSpace(NS_LITERAL_STRING(" ")) // Init of "constant" + kSpace(u" "_ns) // Init of "constant" { mHeadLevel = 0; mHasWrittenCiteBlockquote = false; @@ -794,7 +794,7 @@ nsresult nsPlainTextSerializer::DoOpenContainer(const nsAtom* aTag) { kTabSize; // Check for some maximum value? } } else if (aTag == nsGkAtoms::q) { - Write(NS_LITERAL_STRING("\"")); + Write(u"\""_ns); } // Else make sure we'll separate block level tags, @@ -848,22 +848,22 @@ void nsPlainTextSerializer::OpenContainerForOutputFormatted( } } else if (aTag == nsGkAtoms::sup && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("^")); + Write(u"^"_ns); } else if (aTag == nsGkAtoms::sub && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("_")); + Write(u"_"_ns); } else if (aTag == nsGkAtoms::code && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("|")); + Write(u"|"_ns); } else if ((aTag == nsGkAtoms::strong || aTag == nsGkAtoms::b) && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("*")); + Write(u"*"_ns); } else if ((aTag == nsGkAtoms::em || aTag == nsGkAtoms::i) && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("/")); + Write(u"/"_ns); } else if (aTag == nsGkAtoms::u && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("_")); + Write(u"_"_ns); } /* Container elements are always block elements, so we shouldn't @@ -1000,7 +1000,7 @@ nsresult nsPlainTextSerializer::DoCloseContainer(const nsAtom* aTag) { } mLineBreakDue = true; } else if (aTag == nsGkAtoms::q) { - Write(NS_LITERAL_STRING("\"")); + Write(u"\""_ns); } else if (IsCssBlockLevelElement(mElement)) { // All other blocks get 1 vertical space after them // in formatted mode, otherwise 0. @@ -1057,16 +1057,16 @@ void nsPlainTextSerializer::CloseContainerForOutputFormatted( Write(kSpace); } else if (aTag == nsGkAtoms::code && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("|")); + Write(u"|"_ns); } else if ((aTag == nsGkAtoms::strong || aTag == nsGkAtoms::b) && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("*")); + Write(u"*"_ns); } else if ((aTag == nsGkAtoms::em || aTag == nsGkAtoms::i) && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("/")); + Write(u"/"_ns); } else if (aTag == nsGkAtoms::u && mSettings.GetStructs() && !currentNodeIsConverted) { - Write(NS_LITERAL_STRING("_")); + Write(u"_"_ns); } } @@ -1183,8 +1183,7 @@ nsresult nsPlainTextSerializer::DoAddLeaf(const nsAtom* aTag) { } else if (NS_SUCCEEDED( GetAttributeValue(nsGkAtoms::title, imageDescription)) && !imageDescription.IsEmpty()) { - imageDescription = - NS_LITERAL_STRING(" [") + imageDescription + NS_LITERAL_STRING("] "); + imageDescription = u" ["_ns + imageDescription + u"] "_ns; } Write(imageDescription); diff --git a/dom/base/nsPluginArray.cpp b/dom/base/nsPluginArray.cpp index 676c51ca45ee..fba4826990ea 100644 --- a/dom/base/nsPluginArray.cpp +++ b/dom/base/nsPluginArray.cpp @@ -224,8 +224,8 @@ void nsPluginArray::NotifyHiddenPluginTouched(nsPluginElement* aHiddenElement) { HiddenPluginEventInit init; init.mTag = aHiddenElement->PluginTag(); nsCOMPtr doc = aHiddenElement->GetParentObject()->GetDoc(); - RefPtr event = HiddenPluginEvent::Constructor( - doc, NS_LITERAL_STRING("HiddenPlugin"), init); + RefPtr event = + HiddenPluginEvent::Constructor(doc, u"HiddenPlugin"_ns, init); event->SetTarget(doc); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; diff --git a/dom/base/nsSyncLoadService.cpp b/dom/base/nsSyncLoadService.cpp index ebf95dadd525..a980682ae4c1 100644 --- a/dom/base/nsSyncLoadService.cpp +++ b/dom/base/nsSyncLoadService.cpp @@ -96,7 +96,7 @@ nsForceXMLListener::OnStartRequest(nsIRequest* aRequest) { aRequest->GetStatus(&status); nsCOMPtr channel = do_QueryInterface(aRequest); if (channel && NS_SUCCEEDED(status)) { - channel->SetContentType(NS_LITERAL_CSTRING("text/xml")); + channel->SetContentType("text/xml"_ns); } return mListener->OnStartRequest(aRequest); @@ -130,8 +130,8 @@ nsresult nsSyncLoader::LoadDocument(nsIChannel* aChannel, bool aChannelIsSync, nsCOMPtr http = do_QueryInterface(mChannel); if (http) { rv = http->SetRequestHeader( - NS_LITERAL_CSTRING("Accept"), - NS_LITERAL_CSTRING( + "Accept"_ns, + nsLiteralCString( "text/xml,application/xml,application/xhtml+xml,*/*;q=0.1"), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); @@ -291,7 +291,7 @@ nsresult nsSyncLoadService::LoadDocument( NS_ENSURE_SUCCESS(rv, rv); if (!aForceToXML) { - channel->SetContentType(NS_LITERAL_CSTRING("text/xml")); + channel->SetContentType("text/xml"_ns); } // if the load needs to enforce CORS, then force the load to be async diff --git a/dom/base/nsTreeSanitizer.cpp b/dom/base/nsTreeSanitizer.cpp index fa8939b3a413..1ee2c2686128 100644 --- a/dom/base/nsTreeSanitizer.cpp +++ b/dom/base/nsTreeSanitizer.cpp @@ -1433,16 +1433,14 @@ void nsTreeSanitizer::LogMessage(const char* aMessage, Document* aDoc, nsAutoString msg; msg.Assign(NS_ConvertASCIItoUTF16(aMessage)); if (aElement) { - msg.Append(NS_LITERAL_STRING(" Element: ") + aElement->LocalName() + - NS_LITERAL_STRING(".")); + msg.Append(u" Element: "_ns + aElement->LocalName() + u"."_ns); } if (aAttr) { - msg.Append(NS_LITERAL_STRING(" Attribute: ") + - nsDependentAtomString(aAttr) + NS_LITERAL_STRING(".")); + msg.Append(u" Attribute: "_ns + nsDependentAtomString(aAttr) + u"."_ns); } nsContentUtils::ReportToConsoleNonLocalized( - msg, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), aDoc); + msg, nsIScriptError::warningFlag, "DOM"_ns, aDoc); } } diff --git a/dom/base/nsWindowMemoryReporter.cpp b/dom/base/nsWindowMemoryReporter.cpp index 4f1b6bda5e97..00a820039e27 100644 --- a/dom/base/nsWindowMemoryReporter.cpp +++ b/dom/base/nsWindowMemoryReporter.cpp @@ -117,7 +117,7 @@ nsWindowMemoryReporter* nsWindowMemoryReporter::Get() { } static nsCString GetWindowURISpec(nsGlobalWindowInner* aWindow) { - NS_ENSURE_TRUE(aWindow, NS_LITERAL_CSTRING("")); + NS_ENSURE_TRUE(aWindow, ""_ns); nsCOMPtr doc = aWindow->GetExtantDoc(); if (doc) { @@ -127,18 +127,18 @@ static nsCString GetWindowURISpec(nsGlobalWindowInner* aWindow) { } nsCOMPtr scriptObjPrincipal = do_QueryObject(aWindow); - NS_ENSURE_TRUE(scriptObjPrincipal, NS_LITERAL_CSTRING("")); + NS_ENSURE_TRUE(scriptObjPrincipal, ""_ns); // GetPrincipal() will print a warning if the window does not have an outer // window, so check here for an outer window first. This code is // functionally correct if we leave out the GetOuterWindow() check, but we // end up printing a lot of warnings during debug mochitests. if (!aWindow->GetOuterWindow()) { - return NS_LITERAL_CSTRING(""); + return ""_ns; } nsIPrincipal* principal = scriptObjPrincipal->GetPrincipal(); if (!principal) { - return NS_LITERAL_CSTRING(""); + return ""_ns; } nsCString spec; principal->GetAsciiSpec(spec); @@ -152,7 +152,7 @@ static void AppendWindowURI(nsGlobalWindowInner* aWindow, nsACString& aStr, if (spec.IsEmpty()) { // If we're unable to find a URI, we're dealing with a chrome window with // no document in it (or somesuch), so we call this a "system window". - aStr += NS_LITERAL_CSTRING("[system]"); + aStr += "[system]"_ns; return; } if (aAnonymize && !aWindow->IsChromeWindow()) { @@ -224,29 +224,28 @@ static void CollectWindowReports(nsGlobalWindowInner* aWindow, top = aWindow->GetInProcessTopInternal(); } - windowPath += NS_LITERAL_CSTRING("window-objects/"); + windowPath += "window-objects/"_ns; if (top) { - windowPath += NS_LITERAL_CSTRING("top("); + windowPath += "top("_ns; AppendWindowURI(top->GetCurrentInnerWindowInternal(), windowPath, aAnonymize); windowPath.AppendPrintf(", id=%" PRIu64 ")", top->WindowID()); aTopWindowPaths->Put(aWindow->WindowID(), windowPath); - windowPath += aWindow->IsFrozen() ? NS_LITERAL_CSTRING("/cached/") - : NS_LITERAL_CSTRING("/active/"); + windowPath += aWindow->IsFrozen() ? "/cached/"_ns : "/active/"_ns; } else { if (aGhostWindowIDs->Contains(aWindow->WindowID())) { - windowPath += NS_LITERAL_CSTRING("top(none)/ghost/"); + windowPath += "top(none)/ghost/"_ns; } else { - windowPath += NS_LITERAL_CSTRING("top(none)/detached/"); + windowPath += "top(none)/detached/"_ns; } } - windowPath += NS_LITERAL_CSTRING("window("); + windowPath += "window("_ns; AppendWindowURI(aWindow, windowPath, aAnonymize); - windowPath += NS_LITERAL_CSTRING(")"); + windowPath += ")"_ns; // Use |windowPath|, but replace "explicit/" with "event-counts/". nsCString censusWindowPath(windowPath); @@ -257,21 +256,21 @@ static void CollectWindowReports(nsGlobalWindowInner* aWindow, // Report the size from windowSizes and add to the appropriate total in // aWindowTotalSizes. -#define REPORT_SIZE(_pathTail, _field, _desc) \ - ReportSize(windowPath, _pathTail, windowSizes._field, \ - NS_LITERAL_CSTRING(_desc), aHandleReport, aData); \ +#define REPORT_SIZE(_pathTail, _field, _desc) \ + ReportSize(windowPath, _pathTail, windowSizes._field, \ + nsLiteralCString(_desc), aHandleReport, aData); \ aWindowTotalSizes->_field += windowSizes._field; // Report the size, which is a sum of other sizes, and so doesn't require // updating aWindowTotalSizes. -#define REPORT_SUM_SIZE(_pathTail, _amount, _desc) \ - ReportSize(windowPath, _pathTail, _amount, NS_LITERAL_CSTRING(_desc), \ +#define REPORT_SUM_SIZE(_pathTail, _amount, _desc) \ + ReportSize(windowPath, _pathTail, _amount, nsLiteralCString(_desc), \ aHandleReport, aData); // Like REPORT_SIZE, but for a count. -#define REPORT_COUNT(_pathTail, _field, _desc) \ - ReportCount(censusWindowPath, _pathTail, windowSizes._field, \ - NS_LITERAL_CSTRING(_desc), aHandleReport, aData); \ +#define REPORT_COUNT(_pathTail, _field, _desc) \ + ReportCount(censusWindowPath, _pathTail, windowSizes._field, \ + nsLiteralCString(_desc), aHandleReport, aData); \ aWindowTotalSizes->_field += windowSizes._field; // This SizeOfState contains the SeenPtrs used for all memory reporting of @@ -529,7 +528,7 @@ nsWindowMemoryReporter::CollectReports(nsIHandleReportCallback* aHandleReport, /* process = */ EmptyCString(), path, nsIMemoryReporter::KIND_OTHER, nsIMemoryReporter::UNITS_COUNT, /* amount = */ 1, - /* description = */ NS_LITERAL_CSTRING("A ghost window."), aData); + /* description = */ "A ghost window."_ns, aData); } // clang-format off @@ -566,10 +565,10 @@ nsWindowMemoryReporter::CollectReports(nsIHandleReportCallback* aHandleReport, nsXULPrototypeCache::CollectMemoryReports(aHandleReport, aData); #endif -#define REPORT(_path, _amount, _desc) \ - aHandleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ - KIND_OTHER, UNITS_BYTES, _amount, \ - NS_LITERAL_CSTRING(_desc), aData); +#define REPORT(_path, _amount, _desc) \ + aHandleReport->Callback(EmptyCString(), nsLiteralCString(_path), KIND_OTHER, \ + UNITS_BYTES, _amount, nsLiteralCString(_desc), \ + aData); REPORT("window-objects/dom/element-nodes", windowTotalSizes.mDOMElementNodesSize, diff --git a/dom/base/nsXHTMLContentSerializer.cpp b/dom/base/nsXHTMLContentSerializer.cpp index 2e61fcdd0b5d..42908aa998af 100644 --- a/dom/base/nsXHTMLContentSerializer.cpp +++ b/dom/base/nsXHTMLContentSerializer.cpp @@ -230,8 +230,8 @@ bool nsXHTMLContentSerializer::SerializeAttributes( // Filter out any attribute starting with [-|_]moz nsDependentAtomString attrNameStr(attrName); - if (StringBeginsWith(attrNameStr, NS_LITERAL_STRING("_moz")) || - StringBeginsWith(attrNameStr, NS_LITERAL_STRING("-moz"))) { + if (StringBeginsWith(attrNameStr, u"_moz"_ns) || + StringBeginsWith(attrNameStr, u"-moz"_ns)) { continue; } @@ -287,8 +287,8 @@ bool nsXHTMLContentSerializer::SerializeAttributes( nsAutoString header; aElement->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, header); if (header.LowerCaseEqualsLiteral("content-type")) { - valueStr = NS_LITERAL_STRING("text/html; charset=") + - NS_ConvertASCIItoUTF16(mCharset); + valueStr = + u"text/html; charset="_ns + NS_ConvertASCIItoUTF16(mCharset); } } @@ -345,19 +345,15 @@ bool nsXHTMLContentSerializer::AfterElementStart(nsIContent* aContent, NS_ENSURE_TRUE(AppendIndentation(aStr), false); } NS_ENSURE_TRUE( - AppendToString(NS_LITERAL_STRING(""), aStr), false); + NS_ENSURE_TRUE(AppendToString(u"\">"_ns, aStr), false); } else { - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("\" />"), aStr), false); + NS_ENSURE_TRUE(AppendToString(u"\" />"_ns, aStr), false); } } } @@ -690,9 +686,9 @@ bool nsXHTMLContentSerializer::SerializeLIValueAttribute(nsIContent* aElement, if (offset == 0 && found) { // offset = 0 => LI itself has the value attribute and we did not need to // traverse back. Just serialize value attribute like other tags. - NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"), - valueStr, aStr, false), - false); + NS_ENSURE_TRUE( + SerializeAttr(EmptyString(), u"value"_ns, valueStr, aStr, false), + false); } else if (offset == 1 && !found) { /*(offset = 1 && !found) means either LI is the first child node of OL and LI is not having "value" attribute. @@ -706,9 +702,9 @@ bool nsXHTMLContentSerializer::SerializeLIValueAttribute(nsIContent* aElement, // As serializer needs to use this valueAttr we are creating here, valueStr.AppendInt(startVal + offset); - NS_ENSURE_TRUE(SerializeAttr(EmptyString(), NS_LITERAL_STRING("value"), - valueStr, aStr, false), - false); + NS_ENSURE_TRUE( + SerializeAttr(EmptyString(), u"value"_ns, valueStr, aStr, false), + false); } return true; diff --git a/dom/base/nsXMLContentSerializer.cpp b/dom/base/nsXMLContentSerializer.cpp index 7b44e83cd20b..a5cd26baf6a8 100644 --- a/dom/base/nsXMLContentSerializer.cpp +++ b/dom/base/nsXMLContentSerializer.cpp @@ -241,8 +241,7 @@ nsXMLContentSerializer::AppendCDATASection(nsIContent* aCDATASection, NS_ENSURE_TRUE(AppendToStringConvertLF(data, *mOutput), NS_ERROR_OUT_OF_MEMORY); - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("]]>"), *mOutput), - NS_ERROR_OUT_OF_MEMORY); + NS_ENSURE_TRUE(AppendToString(u"]]>"_ns, *mOutput), NS_ERROR_OUT_OF_MEMORY); return NS_OK; } @@ -287,8 +286,7 @@ nsXMLContentSerializer::AppendProcessingInstruction(ProcessingInstruction* aPI, NS_ENSURE_TRUE(AppendToStringConvertLF(data, *mOutput), NS_ERROR_OUT_OF_MEMORY); } - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("?>"), *mOutput), - NS_ERROR_OUT_OF_MEMORY); + NS_ENSURE_TRUE(AppendToString(u"?>"_ns, *mOutput), NS_ERROR_OUT_OF_MEMORY); MaybeFlagNewlineForRootNode(aPI); @@ -341,8 +339,7 @@ nsXMLContentSerializer::AppendComment(Comment* aComment, int32_t aStartOffset, // could have been preformated by the author NS_ENSURE_TRUE(AppendToStringConvertLF(data, *mOutput), NS_ERROR_OUT_OF_MEMORY); - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING("-->"), *mOutput), - NS_ERROR_OUT_OF_MEMORY); + NS_ENSURE_TRUE(AppendToString(u"-->"_ns, *mOutput), NS_ERROR_OUT_OF_MEMORY); MaybeFlagNewlineForRootNode(aComment); @@ -360,13 +357,13 @@ nsXMLContentSerializer::AppendDoctype(DocumentType* aDocType) { NS_ENSURE_TRUE(MaybeAddNewlineForRootNode(*mOutput), NS_ERROR_OUT_OF_MEMORY); - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(""), aStr); + return AppendToString(u"/>"_ns, aStr); } NS_IMETHODIMP @@ -1043,8 +1037,7 @@ nsXMLContentSerializer::AppendElementEnd(Element* aElement, NS_ENSURE_TRUE(AppendToString(kEndTag, *mOutput), NS_ERROR_OUT_OF_MEMORY); if (!tagPrefix.IsEmpty()) { NS_ENSURE_TRUE(AppendToString(tagPrefix, *mOutput), NS_ERROR_OUT_OF_MEMORY); - NS_ENSURE_TRUE(AppendToString(NS_LITERAL_STRING(":"), *mOutput), - NS_ERROR_OUT_OF_MEMORY); + NS_ENSURE_TRUE(AppendToString(u":"_ns, *mOutput), NS_ERROR_OUT_OF_MEMORY); } NS_ENSURE_TRUE(AppendToString(tagLocalName, *mOutput), NS_ERROR_OUT_OF_MEMORY); @@ -1099,11 +1092,11 @@ nsXMLContentSerializer::AppendDocumentStart(Document* aDocument) { NS_NAMED_LITERAL_STRING(endQuote, "\""); - *mOutput += NS_LITERAL_STRING("AppendLiteral("?>", mozilla::fallible), diff --git a/dom/base/nsXMLContentSerializer.h b/dom/base/nsXMLContentSerializer.h index d6b26772da69..eeb9f04026bf 100644 --- a/dom/base/nsXMLContentSerializer.h +++ b/dom/base/nsXMLContentSerializer.h @@ -20,8 +20,8 @@ #include "nsTArray.h" #include "nsString.h" -#define kIndentStr NS_LITERAL_STRING(" ") -#define kEndTag NS_LITERAL_STRING(" uri, subURI; - nsresult rv = - NS_NewURI(getter_AddRefs(uri), - NS_LITERAL_CSTRING("https://example.com/path/favicon.ico#")); + nsresult rv = NS_NewURI(getter_AddRefs(uri), + "https://example.com/path/favicon.ico#"_ns); ASSERT_TRUE(rv == NS_OK); rv = NS_NewURI(getter_AddRefs(subURI), - NS_LITERAL_CSTRING("http://sub.example.com/favicon.ico?")); + "http://sub.example.com/favicon.ico?"_ns); ASSERT_TRUE(rv == NS_OK); static constexpr IsURIInListMatch patterns[] = { - {NS_LITERAL_CSTRING("bar.com,*.example.com,example.com,foo.com"), true, - true}, - {NS_LITERAL_CSTRING("bar.com,example.com,*.example.com,foo.com"), true, - true}, - {NS_LITERAL_CSTRING("*.example.com,example.com,foo.com"), true, true}, - {NS_LITERAL_CSTRING("example.com,*.example.com,foo.com"), true, true}, - {NS_LITERAL_CSTRING("*.example.com,example.com"), true, true}, - {NS_LITERAL_CSTRING("example.com,*.example.com"), true, true}, - {NS_LITERAL_CSTRING("*.example.com/,example.com/"), true, true}, - {NS_LITERAL_CSTRING("example.com/,*.example.com/"), true, true}, - {NS_LITERAL_CSTRING("*.example.com/pa,example.com/pa"), false, false}, - {NS_LITERAL_CSTRING("example.com/pa,*.example.com/pa"), false, false}, - {NS_LITERAL_CSTRING("*.example.com/pa/,example.com/pa/"), false, false}, - {NS_LITERAL_CSTRING("example.com/pa/,*.example.com/pa/"), false, false}, - {NS_LITERAL_CSTRING("*.example.com/path,example.com/path"), false, false}, - {NS_LITERAL_CSTRING("example.com/path,*.example.com/path"), false, false}, - {NS_LITERAL_CSTRING("*.example.com/path/,example.com/path/"), true, - false}, - {NS_LITERAL_CSTRING("example.com/path/,*.example.com/path/"), true, - false}, - {NS_LITERAL_CSTRING("*.example.com/favicon.ico"), false, true}, - {NS_LITERAL_CSTRING("example.com/path/favicon.ico"), true, false}, - {NS_LITERAL_CSTRING("*.example.com"), false, true}, - {NS_LITERAL_CSTRING("example.com"), true, false}, - {NS_LITERAL_CSTRING("foo.com"), false, false}, - {NS_LITERAL_CSTRING("*.foo.com"), false, false}, + {"bar.com,*.example.com,example.com,foo.com"_ns, true, true}, + {"bar.com,example.com,*.example.com,foo.com"_ns, true, true}, + {"*.example.com,example.com,foo.com"_ns, true, true}, + {"example.com,*.example.com,foo.com"_ns, true, true}, + {"*.example.com,example.com"_ns, true, true}, + {"example.com,*.example.com"_ns, true, true}, + {"*.example.com/,example.com/"_ns, true, true}, + {"example.com/,*.example.com/"_ns, true, true}, + {"*.example.com/pa,example.com/pa"_ns, false, false}, + {"example.com/pa,*.example.com/pa"_ns, false, false}, + {"*.example.com/pa/,example.com/pa/"_ns, false, false}, + {"example.com/pa/,*.example.com/pa/"_ns, false, false}, + {"*.example.com/path,example.com/path"_ns, false, false}, + {"example.com/path,*.example.com/path"_ns, false, false}, + {"*.example.com/path/,example.com/path/"_ns, true, false}, + {"example.com/path/,*.example.com/path/"_ns, true, false}, + {"*.example.com/favicon.ico"_ns, false, true}, + {"example.com/path/favicon.ico"_ns, true, false}, + {"*.example.com"_ns, false, true}, + {"example.com"_ns, true, false}, + {"foo.com"_ns, false, false}, + {"*.foo.com"_ns, false, false}, }; for (auto& entry : patterns) { diff --git a/dom/base/test/gtest/TestMimeType.cpp b/dom/base/test/gtest/TestMimeType.cpp index c19e29edf615..64a2b8f4bdf1 100644 --- a/dom/base/test/gtest/TestMimeType.cpp +++ b/dom/base/test/gtest/TestMimeType.cpp @@ -13,7 +13,7 @@ using mozilla::UniquePtr; TEST(MimeType, EmptyString) { - const auto in = NS_LITERAL_STRING(""); + const auto in = u""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Empty string"; @@ -21,7 +21,7 @@ TEST(MimeType, EmptyString) TEST(MimeType, JustWhitespace) { - const auto in = NS_LITERAL_STRING(" \t\r\n "); + const auto in = u" \t\r\n "_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Just whitespace"; @@ -29,7 +29,7 @@ TEST(MimeType, JustWhitespace) TEST(MimeType, JustBackslash) { - const auto in = NS_LITERAL_STRING("\\"); + const auto in = u"\\"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Just backslash"; @@ -37,7 +37,7 @@ TEST(MimeType, JustBackslash) TEST(MimeType, JustForwardslash) { - const auto in = NS_LITERAL_STRING("/"); + const auto in = u"/"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Just forward slash"; @@ -45,7 +45,7 @@ TEST(MimeType, JustForwardslash) TEST(MimeType, MissingType1) { - const auto in = NS_LITERAL_STRING("/bogus"); + const auto in = u"/bogus"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing type #1"; @@ -53,7 +53,7 @@ TEST(MimeType, MissingType1) TEST(MimeType, MissingType2) { - const auto in = NS_LITERAL_STRING(" \r\n\t/bogus"); + const auto in = u" \r\n\t/bogus"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing type #2"; @@ -61,7 +61,7 @@ TEST(MimeType, MissingType2) TEST(MimeType, MissingSubtype1) { - const auto in = NS_LITERAL_STRING("bogus"); + const auto in = u"bogus"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing subtype #1"; @@ -69,7 +69,7 @@ TEST(MimeType, MissingSubtype1) TEST(MimeType, MissingSubType2) { - const auto in = NS_LITERAL_STRING("bogus/"); + const auto in = u"bogus/"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing subtype #2"; @@ -77,7 +77,7 @@ TEST(MimeType, MissingSubType2) TEST(MimeType, MissingSubType3) { - const auto in = NS_LITERAL_STRING("bogus;"); + const auto in = u"bogus;"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing subtype #3"; @@ -85,7 +85,7 @@ TEST(MimeType, MissingSubType3) TEST(MimeType, MissingSubType4) { - const auto in = NS_LITERAL_STRING("bogus; \r\n\t"); + const auto in = u"bogus; \r\n\t"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Missing subtype #3"; @@ -93,7 +93,7 @@ TEST(MimeType, MissingSubType4) TEST(MimeType, ExtraForwardSlash) { - const auto in = NS_LITERAL_STRING("bogus/bogus/;"); + const auto in = u"bogus/bogus/;"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Extra forward slash"; @@ -101,7 +101,7 @@ TEST(MimeType, ExtraForwardSlash) TEST(MimeType, WhitespaceInType) { - const auto in = NS_LITERAL_STRING("t\re\nx\tt /html"); + const auto in = u"t\re\nx\tt /html"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Type with whitespace"; @@ -109,7 +109,7 @@ TEST(MimeType, WhitespaceInType) TEST(MimeType, WhitespaceInSubtype) { - const auto in = NS_LITERAL_STRING("text/ h\rt\nm\tl"); + const auto in = u"text/ h\rt\nm\tl"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Subtype with whitespace"; @@ -117,7 +117,7 @@ TEST(MimeType, WhitespaceInSubtype) TEST(MimeType, NonAlphanumericMediaType1) { - const auto in = NS_LITERAL_STRING(""); + const auto in = u""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #1"; @@ -125,7 +125,7 @@ TEST(MimeType, NonAlphanumericMediaType1) TEST(MimeType, NonAlphanumericMediaType2) { - const auto in = NS_LITERAL_STRING("(/)"); + const auto in = u"(/)"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #2"; @@ -133,7 +133,7 @@ TEST(MimeType, NonAlphanumericMediaType2) TEST(MimeType, NonAlphanumericMediaType3) { - const auto in = NS_LITERAL_STRING("{/}"); + const auto in = u"{/}"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #3"; @@ -141,7 +141,7 @@ TEST(MimeType, NonAlphanumericMediaType3) TEST(MimeType, NonAlphanumericMediaType4) { - const auto in = NS_LITERAL_STRING("\"/\""); + const auto in = u"\"/\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #4"; @@ -149,7 +149,7 @@ TEST(MimeType, NonAlphanumericMediaType4) TEST(MimeType, NonAlphanumericMediaType5) { - const auto in = NS_LITERAL_STRING("\0/\0"); + const auto in = u"\0/\0"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #5"; @@ -157,7 +157,7 @@ TEST(MimeType, NonAlphanumericMediaType5) TEST(MimeType, NonAlphanumericMediaType6) { - const auto in = NS_LITERAL_STRING("text/html(;doesnot=matter"); + const auto in = u"text/html(;doesnot=matter"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-alphanumeric media type #6"; @@ -165,7 +165,7 @@ TEST(MimeType, NonAlphanumericMediaType6) TEST(MimeType, NonLatin1MediaType1) { - const auto in = NS_LITERAL_STRING("ÿ/ÿ"); + const auto in = u"ÿ/ÿ"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-latin1 media type #1"; @@ -173,7 +173,7 @@ TEST(MimeType, NonLatin1MediaType1) TEST(MimeType, NonLatin1MediaType2) { - const auto in = NS_LITERAL_STRING(u"\x0100/\x0100"); + const auto in = u"\x0100/\x0100"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_FALSE(parsed) << "Non-latin1 media type #2"; @@ -181,52 +181,49 @@ TEST(MimeType, NonLatin1MediaType2) TEST(MimeType, MultipleParameters) { - const auto in = - NS_LITERAL_STRING("text/html;charset=gbk;no=1;charset_=gbk_;yes=2"); + const auto in = u"text/html;charset=gbk;no=1;charset_=gbk_;yes=2"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; nsString out; parsed->Serialize(out); - ASSERT_TRUE(out.Equals( - NS_LITERAL_STRING("text/html;charset=gbk;no=1;charset_=gbk_;yes=2"))) + ASSERT_TRUE(out.Equals(u"text/html;charset=gbk;no=1;charset_=gbk_;yes=2"_ns)) << "Multiple parameters"; } TEST(MimeType, DuplicateParameter1) { - const auto in = - NS_LITERAL_STRING("text/html;charset=gbk;charset=windows-1255"); + const auto in = u"text/html;charset=gbk;charset=windows-1255"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; nsString out; parsed->Serialize(out); - ASSERT_TRUE(out.Equals(NS_LITERAL_STRING("text/html;charset=gbk"))) + ASSERT_TRUE(out.Equals(u"text/html;charset=gbk"_ns)) << "Duplicate parameter #1"; } TEST(MimeType, DuplicateParameter2) { - const auto in = NS_LITERAL_STRING("text/html;charset=();charset=GBK"); + const auto in = u"text/html;charset=();charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; nsString out; parsed->Serialize(out); - ASSERT_TRUE(out.Equals(NS_LITERAL_STRING("text/html;charset=\"()\""))) + ASSERT_TRUE(out.Equals(u"text/html;charset=\"()\""_ns)) << "Duplicate parameter #2"; } TEST(MimeType, CString) { - const auto in = NS_LITERAL_CSTRING("text/html;charset=();charset=GBK"); + const auto in = "text/html;charset=();charset=GBK"_ns; UniquePtr parsed = CMimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; nsCString out; parsed->Serialize(out); - ASSERT_TRUE(out.Equals(NS_LITERAL_CSTRING("text/html;charset=\"()\""))) + ASSERT_TRUE(out.Equals("text/html;charset=\"()\""_ns)) << "Duplicate parameter #2"; } @@ -236,14 +233,13 @@ TEST(MimeType, CString) #endif TEST(MimeType, NonAlphanumericParametersAreQuoted) { - const auto in = NS_LITERAL_STRING("text/html;test=\x00FF\\;charset=gbk"); + const auto in = u"text/html;test=\x00FF\\;charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; nsString out; parsed->Serialize(out); - ASSERT_TRUE(out.Equals( - NS_LITERAL_STRING("text/html;test=\"\x00FF\\\\\";charset=gbk"))) + ASSERT_TRUE(out.Equals(u"text/html;test=\"\x00FF\\\\\";charset=gbk"_ns)) << "Non-alphanumeric parameters are quoted"; } #ifdef _MSC_VER @@ -252,7 +248,7 @@ TEST(MimeType, NonAlphanumericParametersAreQuoted) TEST(MimeType, ParameterQuotedIfHasLeadingWhitespace1) { - const auto in = NS_LITERAL_STRING("text/html;charset= g\\\"bk"); + const auto in = u"text/html;charset= g\\\"bk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -264,7 +260,7 @@ TEST(MimeType, ParameterQuotedIfHasLeadingWhitespace1) TEST(MimeType, ParameterQuotedIfHasLeadingWhitespace2) { - const auto in = NS_LITERAL_STRING("text/html;charset= \"g\\bk\""); + const auto in = u"text/html;charset= \"g\\bk\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -276,7 +272,7 @@ TEST(MimeType, ParameterQuotedIfHasLeadingWhitespace2) TEST(MimeType, ParameterQuotedIfHasInternalWhitespace) { - const auto in = NS_LITERAL_STRING("text/html;charset=g \\b\"k"); + const auto in = u"text/html;charset=g \\b\"k"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -288,7 +284,7 @@ TEST(MimeType, ParameterQuotedIfHasInternalWhitespace) TEST(MimeType, ImproperlyQuotedParameter1) { - const auto in = NS_LITERAL_STRING("x/x;test=\""); + const auto in = u"x/x;test=\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -300,7 +296,7 @@ TEST(MimeType, ImproperlyQuotedParameter1) TEST(MimeType, ImproperlyQuotedParameter2) { - const auto in = NS_LITERAL_STRING("x/x;test=\"\\"); + const auto in = u"x/x;test=\"\\"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -312,7 +308,7 @@ TEST(MimeType, ImproperlyQuotedParameter2) TEST(MimeType, NonLatin1ParameterIgnored) { - const auto in = NS_LITERAL_STRING(u"x/x;test=\xFFFD;x=x"); + const auto in = u"x/x;test=\xFFFD;x=x"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -324,7 +320,7 @@ TEST(MimeType, NonLatin1ParameterIgnored) TEST(MimeType, ParameterIgnoredIfWhitespaceInName1) { - const auto in = NS_LITERAL_STRING("text/html;charset =gbk;charset=123"); + const auto in = u"text/html;charset =gbk;charset=123"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -336,7 +332,7 @@ TEST(MimeType, ParameterIgnoredIfWhitespaceInName1) TEST(MimeType, ParameterIgnoredIfWhitespaceInName2) { - const auto in = NS_LITERAL_STRING("text/html;cha rset =gbk;charset=123"); + const auto in = u"text/html;cha rset =gbk;charset=123"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -348,8 +344,7 @@ TEST(MimeType, ParameterIgnoredIfWhitespaceInName2) TEST(MimeType, WhitespaceTrimmed) { - const auto in = NS_LITERAL_STRING( - "\n\r\t text/plain\n\r\t ;\n\r\t charset=123\n\r\t "); + const auto in = u"\n\r\t text/plain\n\r\t ;\n\r\t charset=123\n\r\t "_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -361,7 +356,7 @@ TEST(MimeType, WhitespaceTrimmed) TEST(MimeType, WhitespaceOnlyParameterIgnored) { - const auto in = NS_LITERAL_STRING("x/x;x= \r\n\t"); + const auto in = u"x/x;x= \r\n\t"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -373,7 +368,7 @@ TEST(MimeType, WhitespaceOnlyParameterIgnored) TEST(MimeType, IncompleteParameterIgnored1) { - const auto in = NS_LITERAL_STRING("x/x;test"); + const auto in = u"x/x;test"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -385,7 +380,7 @@ TEST(MimeType, IncompleteParameterIgnored1) TEST(MimeType, IncompleteParameterIgnored2) { - const auto in = NS_LITERAL_STRING("x/x;test="); + const auto in = u"x/x;test="_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -397,7 +392,7 @@ TEST(MimeType, IncompleteParameterIgnored2) TEST(MimeType, IncompleteParameterIgnored3) { - const auto in = NS_LITERAL_STRING("x/x;test= \r\n\t"); + const auto in = u"x/x;test= \r\n\t"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -409,7 +404,7 @@ TEST(MimeType, IncompleteParameterIgnored3) TEST(MimeType, IncompleteParameterIgnored4) { - const auto in = NS_LITERAL_STRING("text/html;test;charset=gbk"); + const auto in = u"text/html;test;charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -421,7 +416,7 @@ TEST(MimeType, IncompleteParameterIgnored4) TEST(MimeType, IncompleteParameterIgnored5) { - const auto in = NS_LITERAL_STRING("text/html;test=;charset=gbk"); + const auto in = u"text/html;test=;charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -433,7 +428,7 @@ TEST(MimeType, IncompleteParameterIgnored5) TEST(MimeType, EmptyParameterIgnored1) { - const auto in = NS_LITERAL_STRING("text/html ; ; charset=gbk"); + const auto in = u"text/html ; ; charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -445,7 +440,7 @@ TEST(MimeType, EmptyParameterIgnored1) TEST(MimeType, EmptyParameterIgnored2) { - const auto in = NS_LITERAL_STRING("text/html;;;;charset=gbk"); + const auto in = u"text/html;;;;charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -457,7 +452,7 @@ TEST(MimeType, EmptyParameterIgnored2) TEST(MimeType, InvalidParameterIgnored1) { - const auto in = NS_LITERAL_STRING("text/html;';charset=gbk"); + const auto in = u"text/html;';charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -469,7 +464,7 @@ TEST(MimeType, InvalidParameterIgnored1) TEST(MimeType, InvalidParameterIgnored2) { - const auto in = NS_LITERAL_STRING("text/html;\";charset=gbk;=123; =321"); + const auto in = u"text/html;\";charset=gbk;=123; =321"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -481,7 +476,7 @@ TEST(MimeType, InvalidParameterIgnored2) TEST(MimeType, InvalidParameterIgnored3) { - const auto in = NS_LITERAL_STRING("text/html;charset= \"\u007F;charset=GBK"); + const auto in = u"text/html;charset= \"\u007F;charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -493,8 +488,8 @@ TEST(MimeType, InvalidParameterIgnored3) TEST(MimeType, InvalidParameterIgnored4) { - const auto in = NS_LITERAL_STRING( - "text/html;charset=\"\u007F;charset=foo\";charset=GBK;charset="); + const auto in = nsLiteralString( + u"text/html;charset=\"\u007F;charset=foo\";charset=GBK;charset="); UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -506,7 +501,7 @@ TEST(MimeType, InvalidParameterIgnored4) TEST(MimeType, SingleQuotes1) { - const auto in = NS_LITERAL_STRING("text/html;charset='gbk'"); + const auto in = u"text/html;charset='gbk'"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -518,7 +513,7 @@ TEST(MimeType, SingleQuotes1) TEST(MimeType, SingleQuotes2) { - const auto in = NS_LITERAL_STRING("text/html;charset='gbk"); + const auto in = u"text/html;charset='gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -530,7 +525,7 @@ TEST(MimeType, SingleQuotes2) TEST(MimeType, SingleQuotes3) { - const auto in = NS_LITERAL_STRING("text/html;charset=gbk'"); + const auto in = u"text/html;charset=gbk'"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -542,7 +537,7 @@ TEST(MimeType, SingleQuotes3) TEST(MimeType, SingleQuotes4) { - const auto in = NS_LITERAL_STRING("text/html;charset=';charset=GBK"); + const auto in = u"text/html;charset=';charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -554,7 +549,7 @@ TEST(MimeType, SingleQuotes4) TEST(MimeType, SingleQuotes5) { - const auto in = NS_LITERAL_STRING("text/html;charset=''';charset=GBK"); + const auto in = u"text/html;charset=''';charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -566,7 +561,7 @@ TEST(MimeType, SingleQuotes5) TEST(MimeType, DoubleQuotes1) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"gbk\""); + const auto in = u"text/html;charset=\"gbk\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -578,7 +573,7 @@ TEST(MimeType, DoubleQuotes1) TEST(MimeType, DoubleQuotes2) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"gbk"); + const auto in = u"text/html;charset=\"gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -590,7 +585,7 @@ TEST(MimeType, DoubleQuotes2) TEST(MimeType, DoubleQuotes3) { - const auto in = NS_LITERAL_STRING("text/html;charset=gbk\""); + const auto in = u"text/html;charset=gbk\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -602,7 +597,7 @@ TEST(MimeType, DoubleQuotes3) TEST(MimeType, DoubleQuotes4) { - const auto in = NS_LITERAL_STRING("text/html;charset=\" gbk\""); + const auto in = u"text/html;charset=\" gbk\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -614,7 +609,7 @@ TEST(MimeType, DoubleQuotes4) TEST(MimeType, DoubleQuotes5) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"gbk \""); + const auto in = u"text/html;charset=\"gbk \""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -626,7 +621,7 @@ TEST(MimeType, DoubleQuotes5) TEST(MimeType, DoubleQuotes6) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"\\ gbk\""); + const auto in = u"text/html;charset=\"\\ gbk\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -638,7 +633,7 @@ TEST(MimeType, DoubleQuotes6) TEST(MimeType, DoubleQuotes7) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"\\g\\b\\k\""); + const auto in = u"text/html;charset=\"\\g\\b\\k\""_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -650,7 +645,7 @@ TEST(MimeType, DoubleQuotes7) TEST(MimeType, DoubleQuotes8) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"gbk\"x"); + const auto in = u"text/html;charset=\"gbk\"x"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -662,7 +657,7 @@ TEST(MimeType, DoubleQuotes8) TEST(MimeType, DoubleQuotes9) { - const auto in = NS_LITERAL_STRING("text/html;charset=\"\";charset=GBK"); + const auto in = u"text/html;charset=\"\";charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -674,7 +669,7 @@ TEST(MimeType, DoubleQuotes9) TEST(MimeType, DoubleQuotes10) { - const auto in = NS_LITERAL_STRING("text/html;charset=\";charset=GBK"); + const auto in = u"text/html;charset=\";charset=GBK"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -686,7 +681,7 @@ TEST(MimeType, DoubleQuotes10) TEST(MimeType, UnexpectedCodePoints) { - const auto in = NS_LITERAL_STRING("text/html;charset={gbk}"); + const auto in = u"text/html;charset={gbk}"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -698,8 +693,9 @@ TEST(MimeType, UnexpectedCodePoints) TEST(MimeType, LongTypesSubtypesAccepted) { - const auto in = NS_LITERAL_STRING( - "012345678901234567890123456789012345678901234567890123456789012345678901" + const auto in = nsLiteralString( + u"01234567890123456789012345678901234567890123456789012345678901234567890" + u"1" "2345678901234567890123456789012345678901234567890123456789/" "012345678901234567890123456789012345678901234567890123456789012345678901" "2345678901234567890123456789012345678901234567890123456789"); @@ -714,8 +710,8 @@ TEST(MimeType, LongTypesSubtypesAccepted) TEST(MimeType, LongParametersAccepted) { - const auto in = NS_LITERAL_STRING( - "text/" + const auto in = nsLiteralString( + u"text/" "html;" "012345678901234567890123456789012345678901234567890123456789012345678901" "2345678901234567890123456789012345678901234567890123456789=x;charset=" @@ -731,7 +727,7 @@ TEST(MimeType, LongParametersAccepted) TEST(MimeType, AllValidCharactersAccepted1) { - const auto in = NS_LITERAL_STRING( + const auto in = nsLiteralString( u"x/x;x=\"\t " u"!\\\"#$%&'()*+,-./" u"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`" @@ -759,7 +755,7 @@ TEST(MimeType, AllValidCharactersAccepted1) TEST(MimeType, CaseNormalization1) { - const auto in = NS_LITERAL_STRING("TEXT/PLAIN;CHARSET=TEST"); + const auto in = u"TEXT/PLAIN;CHARSET=TEST"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -771,8 +767,8 @@ TEST(MimeType, CaseNormalization1) TEST(MimeType, CaseNormalization2) { - const auto in = NS_LITERAL_STRING( - "!#$%&'*+-.^_`|~" + const auto in = nsLiteralString( + u"!#$%&'*+-.^_`|~" "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/" "!#$%&'*+-.^_`|~" "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz;!#$%&'*+-" @@ -797,7 +793,7 @@ TEST(MimeType, CaseNormalization2) TEST(MimeType, LegacyCommentSyntax1) { - const auto in = NS_LITERAL_STRING("text/html;charset=gbk("); + const auto in = u"text/html;charset=gbk("_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; @@ -809,7 +805,7 @@ TEST(MimeType, LegacyCommentSyntax1) TEST(MimeType, LegacyCommentSyntax2) { - const auto in = NS_LITERAL_STRING("text/html;x=(;charset=gbk"); + const auto in = u"text/html;x=(;charset=gbk"_ns; UniquePtr parsed = MimeType::Parse(in); ASSERT_TRUE(parsed) << "Parsing succeeded"; diff --git a/dom/base/test/gtest/TestParser.cpp b/dom/base/test/gtest/TestParser.cpp index fd70ed2c8fb9..e56f744f3be6 100644 --- a/dom/base/test/gtest/TestParser.cpp +++ b/dom/base/test/gtest/TestParser.cpp @@ -38,8 +38,8 @@ TEST(TestParser, TestParserMain) nsCOMPtr encoder = do_createDocumentEncoder("text/html"); if (!encoder) break; - nsresult rv = encoder->Init(document, NS_LITERAL_STRING("text/html"), - nsIDocumentEncoder::OutputRaw); + nsresult rv = + encoder->Init(document, u"text/html"_ns, nsIDocumentEncoder::OutputRaw); if (NS_FAILED(rv)) break; nsString parsed; rv = encoder->EncodeToString(parsed); diff --git a/dom/battery/BatteryManager.cpp b/dom/battery/BatteryManager.cpp index a536ee9fd1da..0a56f12af138 100644 --- a/dom/battery/BatteryManager.cpp +++ b/dom/battery/BatteryManager.cpp @@ -19,11 +19,10 @@ * We have to use macros here because our leak analysis tool things we are * leaking strings when we have |static const nsString|. Sad :( */ -#define LEVELCHANGE_EVENT_NAME NS_LITERAL_STRING("levelchange") -#define CHARGINGCHANGE_EVENT_NAME NS_LITERAL_STRING("chargingchange") -#define DISCHARGINGTIMECHANGE_EVENT_NAME \ - NS_LITERAL_STRING("dischargingtimechange") -#define CHARGINGTIMECHANGE_EVENT_NAME NS_LITERAL_STRING("chargingtimechange") +#define LEVELCHANGE_EVENT_NAME u"levelchange"_ns +#define CHARGINGCHANGE_EVENT_NAME u"chargingchange"_ns +#define DISCHARGINGTIMECHANGE_EVENT_NAME u"dischargingtimechange"_ns +#define CHARGINGTIMECHANGE_EVENT_NAME u"chargingtimechange"_ns namespace mozilla::dom::battery { diff --git a/dom/bindings/BindingUtils.cpp b/dom/bindings/BindingUtils.cpp index 50b4913be8c0..1deda8011b20 100644 --- a/dom/bindings/BindingUtils.cpp +++ b/dom/bindings/BindingUtils.cpp @@ -3983,8 +3983,8 @@ class GetLocalizedStringRunnable final : public WorkerMainThreadRunnable { GetLocalizedStringRunnable(WorkerPrivate* aWorkerPrivate, const nsAutoCString& aKey, nsAutoString& aLocalizedString) - : WorkerMainThreadRunnable( - aWorkerPrivate, NS_LITERAL_CSTRING("GetLocalizedStringRunnable")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "GetLocalizedStringRunnable"_ns), mKey(aKey), mLocalizedString(aLocalizedString) { MOZ_ASSERT(aWorkerPrivate); @@ -4063,8 +4063,7 @@ void ReportDeprecation(nsIGlobalObject* aGlobal, nsIURI* aURI, new DeprecationReportBody(aGlobal, type, nullptr /* date */, msg, aFileName, aLineNumber, aColumnNumber); - ReportingUtils::Report(aGlobal, nsGkAtoms::deprecation, - NS_LITERAL_STRING("default"), + ReportingUtils::Report(aGlobal, nsGkAtoms::deprecation, u"default"_ns, NS_ConvertUTF8toUTF16(spec), body); } diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 8a9388aeda05..553af163470a 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -12752,7 +12752,7 @@ def getBody(self): delete += dedent( """ if (!IsPlatformObjectSameOrigin(cx, proxy)) { - return ReportCrossOriginDenial(cx, id, NS_LITERAL_CSTRING("delete")); + return ReportCrossOriginDenial(cx, id, "delete"_ns); } // Safe to enter the Realm of proxy now. diff --git a/dom/bindings/RemoteObjectProxy.cpp b/dom/bindings/RemoteObjectProxy.cpp index 292521636c87..42393b390179 100644 --- a/dom/bindings/RemoteObjectProxy.cpp +++ b/dom/bindings/RemoteObjectProxy.cpp @@ -31,7 +31,7 @@ bool RemoteObjectProxyBase::defineProperty( // step 3 and // https://html.spec.whatwg.org/multipage/browsers.html#location-defineownproperty // step 2 - return ReportCrossOriginDenial(aCx, aId, NS_LITERAL_CSTRING("define")); + return ReportCrossOriginDenial(aCx, aId, "define"_ns); } bool RemoteObjectProxyBase::ownPropertyKeys( @@ -60,7 +60,7 @@ bool RemoteObjectProxyBase::delete_(JSContext* aCx, // https://html.spec.whatwg.org/multipage/browsers.html#windowproxy-delete // step 3 and // https://html.spec.whatwg.org/multipage/browsers.html#location-delete step 2 - return ReportCrossOriginDenial(aCx, aId, NS_LITERAL_CSTRING("delete")); + return ReportCrossOriginDenial(aCx, aId, "delete"_ns); } bool RemoteObjectProxyBase::getPrototypeIfOrdinary( diff --git a/dom/bindings/nsScriptErrorWithStack.cpp b/dom/bindings/nsScriptErrorWithStack.cpp index 398dead91f7e..a468f92b0349 100644 --- a/dom/bindings/nsScriptErrorWithStack.cpp +++ b/dom/bindings/nsScriptErrorWithStack.cpp @@ -140,7 +140,7 @@ nsScriptErrorWithStack::ToString(nsACString& /*UTF8*/ aResult) { JSContext* cx = jsapi.cx(); JS::RootedObject stack(cx, mStack); nsCString stackString = FormatStackString(cx, principals, stack); - nsCString combined = message + NS_LITERAL_CSTRING("\n") + stackString; + nsCString combined = message + "\n"_ns + stackString; aResult.Assign(combined); return NS_OK; diff --git a/dom/bindings/test/TestInterfaceIterableDouble.cpp b/dom/bindings/test/TestInterfaceIterableDouble.cpp index 82675542c1b3..d4a37537d363 100644 --- a/dom/bindings/test/TestInterfaceIterableDouble.cpp +++ b/dom/bindings/test/TestInterfaceIterableDouble.cpp @@ -25,12 +25,9 @@ NS_INTERFACE_MAP_END TestInterfaceIterableDouble::TestInterfaceIterableDouble( nsPIDOMWindowInner* aParent) : mParent(aParent) { - mValues.AppendElement(std::pair(NS_LITERAL_STRING("a"), - NS_LITERAL_STRING("b"))); - mValues.AppendElement(std::pair(NS_LITERAL_STRING("c"), - NS_LITERAL_STRING("d"))); - mValues.AppendElement(std::pair(NS_LITERAL_STRING("e"), - NS_LITERAL_STRING("f"))); + mValues.AppendElement(std::pair(u"a"_ns, u"b"_ns)); + mValues.AppendElement(std::pair(u"c"_ns, u"d"_ns)); + mValues.AppendElement(std::pair(u"e"_ns, u"f"_ns)); } // static diff --git a/dom/bindings/test/TestInterfaceIterableDoubleUnion.cpp b/dom/bindings/test/TestInterfaceIterableDoubleUnion.cpp index c512c3afa36f..d8984ac585b8 100644 --- a/dom/bindings/test/TestInterfaceIterableDoubleUnion.cpp +++ b/dom/bindings/test/TestInterfaceIterableDoubleUnion.cpp @@ -27,11 +27,10 @@ TestInterfaceIterableDoubleUnion::TestInterfaceIterableDoubleUnion( : mParent(aParent) { OwningStringOrLong a; a.SetAsLong() = 1; + mValues.AppendElement(std::pair(u"long"_ns, a)); + a.SetAsString() = u"a"_ns; mValues.AppendElement( - std::pair(NS_LITERAL_STRING("long"), a)); - a.SetAsString() = NS_LITERAL_STRING("a"); - mValues.AppendElement( - std::pair(NS_LITERAL_STRING("string"), a)); + std::pair(u"string"_ns, a)); } // static diff --git a/dom/broadcastchannel/BroadcastChannel.cpp b/dom/broadcastchannel/BroadcastChannel.cpp index ec9cc27e1d19..d00e16a04d67 100644 --- a/dom/broadcastchannel/BroadcastChannel.cpp +++ b/dom/broadcastchannel/BroadcastChannel.cpp @@ -130,7 +130,7 @@ BroadcastChannel::BroadcastChannel(nsIGlobalObject* aGlobal, mState(StateActive), mPortUUID(aPortUUID) { MOZ_ASSERT(aGlobal); - KeepAliveIfHasListenersFor(NS_LITERAL_STRING("message")); + KeepAliveIfHasListenersFor(u"message"_ns); } BroadcastChannel::~BroadcastChannel() { @@ -345,7 +345,7 @@ void BroadcastChannel::Shutdown() { mActor = nullptr; } - IgnoreKeepAliveIfHasListenersFor(NS_LITERAL_STRING("message")); + IgnoreKeepAliveIfHasListenersFor(u"message"_ns); } void BroadcastChannel::RemoveDocFromBFCache() { @@ -431,7 +431,7 @@ void BroadcastChannel::MessageReceived(const MessageData& aData) { init.mData = value; RefPtr event = - MessageEvent::Constructor(this, NS_LITERAL_STRING("message"), init); + MessageEvent::Constructor(this, u"message"_ns, init); event->SetTrusted(true); @@ -450,7 +450,7 @@ void BroadcastChannel::DispatchError(JSContext* aCx) { init.mOrigin = mOriginNoSuffix; RefPtr event = - MessageEvent::Constructor(this, NS_LITERAL_STRING("messageerror"), init); + MessageEvent::Constructor(this, u"messageerror"_ns, init); event->SetTrusted(true); DispatchEvent(*event); diff --git a/dom/cache/AutoUtils.cpp b/dom/cache/AutoUtils.cpp index 8d55f30420fe..f636582bae09 100644 --- a/dom/cache/AutoUtils.cpp +++ b/dom/cache/AutoUtils.cpp @@ -215,7 +215,7 @@ bool MatchInPutList(const InternalRequest& aRequest, nsCString varyHeaders; ErrorResult rv; - cachedResponseHeaders->Get(NS_LITERAL_CSTRING("vary"), varyHeaders, rv); + cachedResponseHeaders->Get("vary"_ns, varyHeaders, rv); MOZ_ALWAYS_TRUE(!rv.Failed()); // Assume the vary headers match until we find a conflict diff --git a/dom/cache/CacheOpParent.cpp b/dom/cache/CacheOpParent.cpp index d050f70d84ad..08486c3e982c 100644 --- a/dom/cache/CacheOpParent.cpp +++ b/dom/cache/CacheOpParent.cpp @@ -271,8 +271,7 @@ void CacheOpParent::ProcessCrossOriginResourcePolicyHeader( corp.Assign(EmptyCString()); for (auto headerIt = it->mValue.headers().cbegin(); headerIt != it->mValue.headers().cend(); ++headerIt) { - if (headerIt->name().Equals( - NS_LITERAL_CSTRING("Cross-Origin-Resource-Policy"))) { + if (headerIt->name().Equals("Cross-Origin-Resource-Policy"_ns)) { corp = headerIt->value(); break; } diff --git a/dom/cache/DBAction.cpp b/dom/cache/DBAction.cpp index 096b9b8b20d3..eb31779ac95b 100644 --- a/dom/cache/DBAction.cpp +++ b/dom/cache/DBAction.cpp @@ -90,7 +90,7 @@ void DBAction::RunOnTarget(Resolver* aResolver, const QuotaInfo& aQuotaInfo, return; } - rv = dbDir->Append(NS_LITERAL_STRING("cache")); + rv = dbDir->Append(u"cache"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { aResolver->Resolve(rv); return; @@ -209,14 +209,12 @@ nsresult OpenDBConnection(const QuotaInfo& aQuotaInfo, nsIFile* aDBFile, const nsCString directoryLockIdClause = aQuotaInfo.mDirectoryLockId >= 0 - ? NS_LITERAL_CSTRING("&directoryLockId=") + - IntCString(aQuotaInfo.mDirectoryLockId) + ? "&directoryLockId="_ns + IntCString(aQuotaInfo.mDirectoryLockId) : EmptyCString(); - rv = - NS_MutateURI(mutator) - .SetQuery(NS_LITERAL_CSTRING("cache=private") + directoryLockIdClause) - .Finalize(dbFileUrl); + rv = NS_MutateURI(mutator) + .SetQuery("cache=private"_ns + directoryLockIdClause) + .Finalize(dbFileUrl); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/cache/DBSchema.cpp b/dom/cache/DBSchema.cpp index 92257d339d41..e693802f29a4 100644 --- a/dom/cache/DBSchema.cpp +++ b/dom/cache/DBSchema.cpp @@ -411,8 +411,8 @@ class MOZ_RAII AutoDisableForeignKeyChecking { explicit AutoDisableForeignKeyChecking(mozIStorageConnection* aConn) : mConn(aConn), mForeignKeyCheckingDisabled(false) { nsCOMPtr state; - nsresult rv = mConn->CreateStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_keys;"), getter_AddRefs(state)); + nsresult rv = mConn->CreateStatement("PRAGMA foreign_keys;"_ns, + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -430,8 +430,7 @@ class MOZ_RAII AutoDisableForeignKeyChecking { } if (mode) { - nsresult rv = mConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA foreign_keys = OFF;")); + nsresult rv = mConn->ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -441,8 +440,7 @@ class MOZ_RAII AutoDisableForeignKeyChecking { ~AutoDisableForeignKeyChecking() { if (mForeignKeyCheckingDisabled) { - nsresult rv = mConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA foreign_keys = ON;")); + nsresult rv = mConn->ExecuteSimpleSQL("PRAGMA foreign_keys = ON;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -569,7 +567,7 @@ nsresult CreateOrMigrateSchema(mozIStorageConnection* aConn) { if (needVacuum) { // Unfortunately, this must be performed outside of the transaction. - aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM")); + aConn->ExecuteSimpleSQL("VACUUM"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -634,8 +632,7 @@ nsresult InitializeConnection(mozIStorageConnection* aConn) { // pragma above fails silently. #ifdef DEBUG nsCOMPtr state; - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA auto_vacuum;"), - getter_AddRefs(state)); + rv = aConn->CreateStatement("PRAGMA auto_vacuum;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -666,14 +663,14 @@ nsresult CreateCacheId(mozIStorageConnection* aConn, CacheId* aCacheIdOut) { MOZ_DIAGNOSTIC_ASSERT(aConn); MOZ_DIAGNOSTIC_ASSERT(aCacheIdOut); - nsresult rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO caches DEFAULT VALUES;")); + nsresult rv = + aConn->ExecuteSimpleSQL("INSERT INTO caches DEFAULT VALUES;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } nsCOMPtr state; - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT last_insert_rowid()"), + rv = aConn->CreateStatement("SELECT last_insert_rowid()"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -729,14 +726,13 @@ nsresult DeleteCacheId(mozIStorageConnection* aConn, CacheId aCacheId, // Delete the remainder of the cache using cascade semantics. nsCOMPtr state; - rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM caches WHERE id=:id;"), - getter_AddRefs(state)); + rv = aConn->CreateStatement("DELETE FROM caches WHERE id=:id;"_ns, + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("id"), aCacheId); + rv = state->BindInt64ByName("id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -760,14 +756,14 @@ nsresult IsCacheOrphaned(mozIStorageConnection* aConn, CacheId aCacheId, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT COUNT(*) FROM storage WHERE cache_id=:cache_id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("cache_id"), aCacheId); + rv = state->BindInt64ByName("cache_id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -794,8 +790,8 @@ nsresult FindOrphanedCacheIds(mozIStorageConnection* aConn, nsTArray& aOrphanedListOut) { nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT id FROM caches " - "WHERE id NOT IN (SELECT cache_id from storage);"), + "SELECT id FROM caches " + "WHERE id NOT IN (SELECT cache_id from storage);"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -821,8 +817,8 @@ nsresult FindOverallPaddingSize(mozIStorageConnection* aConn, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT response_padding_size FROM entries " - "WHERE response_padding_size IS NOT NULL;"), + "SELECT response_padding_size FROM entries " + "WHERE response_padding_size IS NOT NULL;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -854,7 +850,7 @@ nsresult GetKnownBodyIds(mozIStorageConnection* aConn, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT request_body_id, response_body_id FROM entries;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -963,7 +959,7 @@ nsresult CachePut(mozIStorageConnection* aConn, CacheId aCacheId, MOZ_DIAGNOSTIC_ASSERT(aConn); MOZ_DIAGNOSTIC_ASSERT(aDeletedPaddingSizeOut); - CacheQueryParams params(false, false, false, false, NS_LITERAL_STRING("")); + CacheQueryParams params(false, false, false, false, u""_ns); AutoTArray matches; nsresult rv = QueryCache(aConn, aCacheId, aRequest, params, matches); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -1114,14 +1110,14 @@ nsresult StorageMatch(mozIStorageConnection* aConn, Namespace aNamespace, nsCOMPtr state; rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT cache_id FROM storage WHERE " - "namespace=:namespace ORDER BY rowid;"), + "SELECT cache_id FROM storage WHERE " + "namespace=:namespace ORDER BY rowid;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("namespace"), aNamespace); + rv = state->BindInt32ByName("namespace"_ns, aNamespace); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1180,7 +1176,7 @@ nsresult StorageGetCacheId(mozIStorageConnection* aConn, Namespace aNamespace, return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("namespace"), aNamespace); + rv = state->BindInt32ByName("namespace"_ns, aNamespace); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1211,24 +1207,24 @@ nsresult StoragePutCache(mozIStorageConnection* aConn, Namespace aNamespace, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO storage (namespace, key, cache_id) " - "VALUES (:namespace, :key, :cache_id);"), + "INSERT INTO storage (namespace, key, cache_id) " + "VALUES (:namespace, :key, :cache_id);"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("namespace"), aNamespace); + rv = state->BindInt32ByName("namespace"_ns, aNamespace); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindStringAsBlobByName(NS_LITERAL_CSTRING("key"), aKey); + rv = state->BindStringAsBlobByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("cache_id"), aCacheId); + rv = state->BindInt64ByName("cache_id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1258,7 +1254,7 @@ nsresult StorageForgetCache(mozIStorageConnection* aConn, Namespace aNamespace, return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("namespace"), aNamespace); + rv = state->BindInt32ByName("namespace"_ns, aNamespace); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1278,14 +1274,14 @@ nsresult StorageGetKeys(mozIStorageConnection* aConn, Namespace aNamespace, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT key FROM storage WHERE namespace=:namespace ORDER BY rowid;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("namespace"), aNamespace); + rv = state->BindInt32ByName("namespace"_ns, aNamespace); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1313,14 +1309,14 @@ nsresult QueryAll(mozIStorageConnection* aConn, CacheId aCacheId, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id FROM entries WHERE cache_id=:cache_id ORDER BY id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("cache_id"), aCacheId); + rv = state->BindInt64ByName("cache_id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1378,7 +1374,7 @@ nsresult QueryCache(mozIStorageConnection* aConn, CacheId aCacheId, return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("cache_id"), aCacheId); + rv = state->BindInt64ByName("cache_id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1395,8 +1391,8 @@ nsresult QueryCache(mozIStorageConnection* aConn, CacheId aCacheId, return rv; } - rv = state->BindUTF8StringAsBlobByName( - NS_LITERAL_CSTRING("url_no_query_hash"), urlWithoutQueryHash); + rv = state->BindUTF8StringAsBlobByName("url_no_query_hash"_ns, + urlWithoutQueryHash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1408,22 +1404,20 @@ nsresult QueryCache(mozIStorageConnection* aConn, CacheId aCacheId, return rv; } - rv = state->BindUTF8StringAsBlobByName(NS_LITERAL_CSTRING("url_query_hash"), - urlQueryHash); + rv = state->BindUTF8StringAsBlobByName("url_query_hash"_ns, urlQueryHash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("url_no_query"), + rv = state->BindUTF8StringByName("url_no_query"_ns, aRequest.urlWithoutQuery()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } if (!aParams.ignoreSearch()) { - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("url_query"), - aRequest.urlQuery()); + rv = state->BindUTF8StringByName("url_query"_ns, aRequest.urlQuery()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1475,15 +1469,15 @@ nsresult MatchByVaryHeader(mozIStorageConnection* aConn, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT value FROM response_headers " - "WHERE name='vary' COLLATE NOCASE " - "AND entry_id=:entry_id;"), + "SELECT value FROM response_headers " + "WHERE name='vary' COLLATE NOCASE " + "AND entry_id=:entry_id;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), entryId); + rv = state->BindInt32ByName("entry_id"_ns, entryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1508,14 +1502,14 @@ nsresult MatchByVaryHeader(mozIStorageConnection* aConn, state->Reset(); rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT name, value FROM request_headers " - "WHERE entry_id=:entry_id;"), + "SELECT name, value FROM request_headers " + "WHERE entry_id=:entry_id;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), entryId); + rv = state->BindInt32ByName("entry_id"_ns, entryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1741,7 +1735,7 @@ nsresult DeleteEntries(mozIStorageConnection* aConn, // Dependent records removed via ON DELETE CASCADE - query = NS_LITERAL_CSTRING("DELETE FROM entries WHERE id IN ("); + query = "DELETE FROM entries WHERE id IN ("_ns; AppendListParamsToQuery(query, aEntryIdList, aPos, aLen); query.AppendLiteral(")"); @@ -1787,7 +1781,7 @@ nsresult InsertSecurityInfo(mozIStorageConnection* aConn, // comparison of the large data column. (This was verified with EXPLAIN.) nsCOMPtr state; rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( // Note that hash and data are blobs, but we can use = here since the // columns are NOT NULL. "SELECT id, refcount FROM security_info WHERE hash=:hash AND " @@ -1797,12 +1791,12 @@ nsresult InsertSecurityInfo(mozIStorageConnection* aConn, return rv; } - rv = state->BindUTF8StringAsBlobByName(NS_LITERAL_CSTRING("hash"), hash); + rv = state->BindUTF8StringAsBlobByName("hash"_ns, hash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringAsBlobByName(NS_LITERAL_CSTRING("data"), aData); + rv = state->BindUTF8StringAsBlobByName("data"_ns, aData); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1831,19 +1825,19 @@ nsresult InsertSecurityInfo(mozIStorageConnection* aConn, refcount += 1; rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "UPDATE security_info SET refcount=:refcount WHERE id=:id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("refcount"), refcount); + rv = state->BindInt32ByName("refcount"_ns, refcount); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), *aIdOut); + rv = state->BindInt32ByName("id"_ns, *aIdOut); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1859,19 +1853,19 @@ nsresult InsertSecurityInfo(mozIStorageConnection* aConn, // This is a new security info blob. Create a new row in the security table // with an initial refcount of 1. rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO security_info (hash, data, refcount) " - "VALUES (:hash, :data, 1);"), + "INSERT INTO security_info (hash, data, refcount) " + "VALUES (:hash, :data, 1);"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringAsBlobByName(NS_LITERAL_CSTRING("hash"), hash); + rv = state->BindUTF8StringAsBlobByName("hash"_ns, hash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringAsBlobByName(NS_LITERAL_CSTRING("data"), aData); + rv = state->BindUTF8StringAsBlobByName("data"_ns, aData); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1881,7 +1875,7 @@ nsresult InsertSecurityInfo(mozIStorageConnection* aConn, return rv; } - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT last_insert_rowid()"), + rv = aConn->CreateStatement("SELECT last_insert_rowid()"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -1906,13 +1900,13 @@ nsresult DeleteSecurityInfo(mozIStorageConnection* aConn, int32_t aId, // First, we need to determine the current refcount for this security blob. nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT refcount FROM security_info WHERE id=:id;"), + "SELECT refcount FROM security_info WHERE id=:id;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), aId); + rv = state->BindInt32ByName("id"_ns, aId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1937,14 +1931,13 @@ nsresult DeleteSecurityInfo(mozIStorageConnection* aConn, int32_t aId, // If the last reference to this security blob was removed we can // just remove the entire row. if (newCount == 0) { - rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM security_info WHERE id=:id;"), - getter_AddRefs(state)); + rv = aConn->CreateStatement("DELETE FROM security_info WHERE id=:id;"_ns, + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), aId); + rv = state->BindInt32ByName("id"_ns, aId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1960,19 +1953,19 @@ nsresult DeleteSecurityInfo(mozIStorageConnection* aConn, int32_t aId, // Otherwise update the refcount in the table to reflect the reduced // number of references to the security blob. rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "UPDATE security_info SET refcount=:refcount WHERE id=:id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("refcount"), newCount); + rv = state->BindInt32ByName("refcount"_ns, newCount); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), aId); + rv = state->BindInt32ByName("id"_ns, aId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2024,71 +2017,70 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, } nsCOMPtr state; - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("INSERT INTO entries (" - "request_method, " - "request_url_no_query, " - "request_url_no_query_hash, " - "request_url_query, " - "request_url_query_hash, " - "request_url_fragment, " - "request_referrer, " - "request_referrer_policy, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_integrity, " - "request_body_id, " - "response_type, " - "response_status, " - "response_status_text, " - "response_headers_guard, " - "response_body_id, " - "response_security_info_id, " - "response_principal_info, " - "response_padding_size, " - "cache_id " - ") VALUES (" - ":request_method, " - ":request_url_no_query, " - ":request_url_no_query_hash, " - ":request_url_query, " - ":request_url_query_hash, " - ":request_url_fragment, " - ":request_referrer, " - ":request_referrer_policy, " - ":request_headers_guard, " - ":request_mode, " - ":request_credentials, " - ":request_contentpolicytype, " - ":request_cache, " - ":request_redirect, " - ":request_integrity, " - ":request_body_id, " - ":response_type, " - ":response_status, " - ":response_status_text, " - ":response_headers_guard, " - ":response_body_id, " - ":response_security_info_id, " - ":response_principal_info, " - ":response_padding_size, " - ":cache_id " - ");"), + rv = aConn->CreateStatement(nsLiteralCString("INSERT INTO entries (" + "request_method, " + "request_url_no_query, " + "request_url_no_query_hash, " + "request_url_query, " + "request_url_query_hash, " + "request_url_fragment, " + "request_referrer, " + "request_referrer_policy, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_integrity, " + "request_body_id, " + "response_type, " + "response_status, " + "response_status_text, " + "response_headers_guard, " + "response_body_id, " + "response_security_info_id, " + "response_principal_info, " + "response_padding_size, " + "cache_id " + ") VALUES (" + ":request_method, " + ":request_url_no_query, " + ":request_url_no_query_hash, " + ":request_url_query, " + ":request_url_query_hash, " + ":request_url_fragment, " + ":request_referrer, " + ":request_referrer_policy, " + ":request_headers_guard, " + ":request_mode, " + ":request_credentials, " + ":request_contentpolicytype, " + ":request_cache, " + ":request_redirect, " + ":request_integrity, " + ":request_body_id, " + ":response_type, " + ":response_status, " + ":response_status_text, " + ":response_headers_guard, " + ":response_body_id, " + ":response_security_info_id, " + ":response_principal_info, " + ":response_padding_size, " + ":cache_id " + ");"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("request_method"), - aRequest.method()); + rv = state->BindUTF8StringByName("request_method"_ns, aRequest.method()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("request_url_no_query"), + rv = state->BindUTF8StringByName("request_url_no_query"_ns, aRequest.urlWithoutQuery()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2100,14 +2092,13 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, return rv; } - rv = state->BindUTF8StringAsBlobByName( - NS_LITERAL_CSTRING("request_url_no_query_hash"), urlWithoutQueryHash); + rv = state->BindUTF8StringAsBlobByName("request_url_no_query_hash"_ns, + urlWithoutQueryHash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("request_url_query"), - aRequest.urlQuery()); + rv = state->BindUTF8StringByName("request_url_query"_ns, aRequest.urlQuery()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2117,103 +2108,99 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringAsBlobByName( - NS_LITERAL_CSTRING("request_url_query_hash"), urlQueryHash); + rv = state->BindUTF8StringAsBlobByName("request_url_query_hash"_ns, + urlQueryHash); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("request_url_fragment"), + rv = state->BindUTF8StringByName("request_url_fragment"_ns, aRequest.urlFragment()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindStringByName(NS_LITERAL_CSTRING("request_referrer"), - aRequest.referrer()); + rv = state->BindStringByName("request_referrer"_ns, aRequest.referrer()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_referrer_policy"), + rv = state->BindInt32ByName("request_referrer_policy"_ns, static_cast(aRequest.referrerPolicy())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_headers_guard"), + rv = state->BindInt32ByName("request_headers_guard"_ns, static_cast(aRequest.headersGuard())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_mode"), + rv = state->BindInt32ByName("request_mode"_ns, static_cast(aRequest.mode())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_credentials"), + rv = state->BindInt32ByName("request_credentials"_ns, static_cast(aRequest.credentials())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = state->BindInt32ByName( - NS_LITERAL_CSTRING("request_contentpolicytype"), + "request_contentpolicytype"_ns, static_cast(aRequest.contentPolicyType())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_cache"), + rv = state->BindInt32ByName("request_cache"_ns, static_cast(aRequest.requestCache())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("request_redirect"), + rv = state->BindInt32ByName("request_redirect"_ns, static_cast(aRequest.requestRedirect())); - rv = state->BindStringByName(NS_LITERAL_CSTRING("request_integrity"), - aRequest.integrity()); + rv = state->BindStringByName("request_integrity"_ns, aRequest.integrity()); - rv = BindId(state, NS_LITERAL_CSTRING("request_body_id"), aRequestBodyId); + rv = BindId(state, "request_body_id"_ns, aRequestBodyId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("response_type"), + rv = state->BindInt32ByName("response_type"_ns, static_cast(aResponse.type())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("response_status"), - aResponse.status()); + rv = state->BindInt32ByName("response_status"_ns, aResponse.status()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("response_status_text"), + rv = state->BindUTF8StringByName("response_status_text"_ns, aResponse.statusText()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("response_headers_guard"), + rv = state->BindInt32ByName("response_headers_guard"_ns, static_cast(aResponse.headersGuard())); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = BindId(state, NS_LITERAL_CSTRING("response_body_id"), aResponseBodyId); + rv = BindId(state, "response_body_id"_ns, aResponseBodyId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } if (aResponse.channelInfo().securityInfo().IsEmpty()) { - rv = state->BindNullByName(NS_LITERAL_CSTRING("response_security_info_id")); + rv = state->BindNullByName("response_security_info_id"_ns); } else { - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("response_security_info_id"), - securityId); + rv = state->BindInt32ByName("response_security_info_id"_ns, securityId); } if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2236,27 +2223,27 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, serializedInfo.Append(suffix); } - rv = state->BindUTF8StringByName( - NS_LITERAL_CSTRING("response_principal_info"), serializedInfo); + rv = + state->BindUTF8StringByName("response_principal_info"_ns, serializedInfo); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } if (aResponse.paddingSize() == InternalResponse::UNKNOWN_PADDING_SIZE) { MOZ_DIAGNOSTIC_ASSERT(aResponse.type() != ResponseType::Opaque); - rv = state->BindNullByName(NS_LITERAL_CSTRING("response_padding_size")); + rv = state->BindNullByName("response_padding_size"_ns); } else { MOZ_DIAGNOSTIC_ASSERT(aResponse.paddingSize() >= 0); MOZ_DIAGNOSTIC_ASSERT(aResponse.type() == ResponseType::Opaque); - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("response_padding_size"), + rv = state->BindInt64ByName("response_padding_size"_ns, aResponse.paddingSize()); } if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt64ByName(NS_LITERAL_CSTRING("cache_id"), aCacheId); + rv = state->BindInt64ByName("cache_id"_ns, aCacheId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2266,7 +2253,7 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, return rv; } - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT last_insert_rowid()"), + rv = aConn->CreateStatement("SELECT last_insert_rowid()"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2285,11 +2272,11 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, } rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO request_headers (" - "name, " - "value, " - "entry_id " - ") VALUES (:name, :value, :entry_id)"), + nsLiteralCString("INSERT INTO request_headers (" + "name, " + "value, " + "entry_id " + ") VALUES (:name, :value, :entry_id)"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2297,19 +2284,17 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, const nsTArray& requestHeaders = aRequest.headers(); for (uint32_t i = 0; i < requestHeaders.Length(); ++i) { - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("name"), - requestHeaders[i].name()); + rv = state->BindUTF8StringByName("name"_ns, requestHeaders[i].name()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), - requestHeaders[i].value()); + rv = state->BindUTF8StringByName("value"_ns, requestHeaders[i].value()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), entryId); + rv = state->BindInt32ByName("entry_id"_ns, entryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2321,11 +2306,11 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, } rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO response_headers (" - "name, " - "value, " - "entry_id " - ") VALUES (:name, :value, :entry_id)"), + nsLiteralCString("INSERT INTO response_headers (" + "name, " + "value, " + "entry_id " + ") VALUES (:name, :value, :entry_id)"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2333,19 +2318,17 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, const nsTArray& responseHeaders = aResponse.headers(); for (uint32_t i = 0; i < responseHeaders.Length(); ++i) { - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("name"), - responseHeaders[i].name()); + rv = state->BindUTF8StringByName("name"_ns, responseHeaders[i].name()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), - responseHeaders[i].value()); + rv = state->BindUTF8StringByName("value"_ns, responseHeaders[i].value()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), entryId); + rv = state->BindInt32ByName("entry_id"_ns, entryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2356,25 +2339,23 @@ nsresult InsertEntry(mozIStorageConnection* aConn, CacheId aCacheId, } } - rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO response_url_list (" - "url, " - "entry_id " - ") VALUES (:url, :entry_id)"), - getter_AddRefs(state)); + rv = aConn->CreateStatement(nsLiteralCString("INSERT INTO response_url_list (" + "url, " + "entry_id " + ") VALUES (:url, :entry_id)"), + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } const nsTArray& responseUrlList = aResponse.urlList(); for (uint32_t i = 0; i < responseUrlList.Length(); ++i) { - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("url"), - responseUrlList[i]); + rv = state->BindUTF8StringByName("url"_ns, responseUrlList[i]); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), entryId); + rv = state->BindInt32ByName("entry_id"_ns, entryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2396,26 +2377,25 @@ nsresult ReadResponse(mozIStorageConnection* aConn, EntryId aEntryId, nsCOMPtr state; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( - "SELECT " - "entries.response_type, " - "entries.response_status, " - "entries.response_status_text, " - "entries.response_headers_guard, " - "entries.response_body_id, " - "entries.response_principal_info, " - "entries.response_padding_size, " - "security_info.data " - "FROM entries " - "LEFT OUTER JOIN security_info " - "ON entries.response_security_info_id=security_info.id " - "WHERE entries.id=:id;"), + nsLiteralCString("SELECT " + "entries.response_type, " + "entries.response_status, " + "entries.response_status_text, " + "entries.response_headers_guard, " + "entries.response_body_id, " + "entries.response_principal_info, " + "entries.response_padding_size, " + "security_info.data " + "FROM entries " + "LEFT OUTER JOIN security_info " + "ON entries.response_security_info_id=security_info.id " + "WHERE entries.id=:id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), aEntryId); + rv = state->BindInt32ByName("id"_ns, aEntryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2540,17 +2520,17 @@ nsresult ReadResponse(mozIStorageConnection* aConn, EntryId aEntryId, return rv; } - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "name, " - "value " - "FROM response_headers " - "WHERE entry_id=:entry_id;"), + rv = aConn->CreateStatement(nsLiteralCString("SELECT " + "name, " + "value " + "FROM response_headers " + "WHERE entry_id=:entry_id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), aEntryId); + rv = state->BindInt32ByName("entry_id"_ns, aEntryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2571,16 +2551,16 @@ nsresult ReadResponse(mozIStorageConnection* aConn, EntryId aEntryId, aSavedResponseOut->mValue.headers().AppendElement(header); } - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "url " - "FROM response_url_list " - "WHERE entry_id=:entry_id;"), + rv = aConn->CreateStatement(nsLiteralCString("SELECT " + "url " + "FROM response_url_list " + "WHERE entry_id=:entry_id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), aEntryId); + rv = state->BindInt32ByName("entry_id"_ns, aEntryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2606,29 +2586,29 @@ nsresult ReadRequest(mozIStorageConnection* aConn, EntryId aEntryId, MOZ_DIAGNOSTIC_ASSERT(aSavedRequestOut); nsCOMPtr state; nsresult rv = - aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "request_method, " - "request_url_no_query, " - "request_url_query, " - "request_url_fragment, " - "request_referrer, " - "request_referrer_policy, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_integrity, " - "request_body_id " - "FROM entries " - "WHERE id=:id;"), + aConn->CreateStatement(nsLiteralCString("SELECT " + "request_method, " + "request_url_no_query, " + "request_url_query, " + "request_url_fragment, " + "request_referrer, " + "request_referrer_policy, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_integrity, " + "request_body_id " + "FROM entries " + "WHERE id=:id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("id"), aEntryId); + rv = state->BindInt32ByName("id"_ns, aEntryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2724,17 +2704,17 @@ nsresult ReadRequest(mozIStorageConnection* aConn, EntryId aEntryId, return rv; } } - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "name, " - "value " - "FROM request_headers " - "WHERE entry_id=:entry_id;"), + rv = aConn->CreateStatement(nsLiteralCString("SELECT " + "name, " + "value " + "FROM request_headers " + "WHERE entry_id=:entry_id;"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindInt32ByName(NS_LITERAL_CSTRING("entry_id"), aEntryId); + rv = state->BindInt32ByName("entry_id"_ns, aEntryId); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2857,7 +2837,7 @@ nsresult CreateAndBindKeyStatement(mozIStorageConnection* aConn, } if (!aKey.IsEmpty()) { - rv = state->BindStringAsBlobByName(NS_LITERAL_CSTRING("key"), aKey); + rv = state->BindStringAsBlobByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2898,8 +2878,8 @@ nsresult HashCString(nsICryptoHash* aCrypto, const nsACString& aIn, nsresult IncrementalVacuum(mozIStorageConnection* aConn) { // Determine how much free space is in the database. nsCOMPtr state; - nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("PRAGMA freelist_count;"), getter_AddRefs(state)); + nsresult rv = aConn->CreateStatement("PRAGMA freelist_count;"_ns, + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2944,7 +2924,7 @@ nsresult IncrementalVacuum(mozIStorageConnection* aConn) { // Verify that our incremental vacuum actually did something #ifdef DEBUG - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA freelist_count;"), + rv = aConn->CreateStatement("PRAGMA freelist_count;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -2989,9 +2969,8 @@ nsresult GetEffectiveSchemaVersion(mozIStorageConnection* aConn, // was the first release with this functionality, shipping 3.16.2.) nsCOMPtr stmt; nsresult rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( - "SELECT name FROM pragma_table_info('entries') WHERE " - "name = 'response_padding_size'"), + nsLiteralCString("SELECT name FROM pragma_table_info('entries') WHERE " + "name = 'response_padding_size'"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3061,9 +3040,8 @@ nsresult Validate(mozIStorageConnection* aConn) { // Read the schema from the sqlite_master table and compare. nsCOMPtr state; - rv = aConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT name, type, sql FROM sqlite_master;"), - getter_AddRefs(state)); + rv = aConn->CreateStatement("SELECT name, type, sql FROM sqlite_master;"_ns, + getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3160,23 +3138,21 @@ Migration sMigrationList[] = { }; uint32_t sMigrationListLength = sizeof(sMigrationList) / sizeof(Migration); nsresult RewriteEntriesSchema(mozIStorageConnection* aConn) { - nsresult rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA writable_schema = ON")); + nsresult rv = aConn->ExecuteSimpleSQL("PRAGMA writable_schema = ON"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } nsCOMPtr state; rv = aConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "UPDATE sqlite_master SET sql=:sql WHERE name='entries'"), getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = state->BindUTF8StringByName(NS_LITERAL_CSTRING("sql"), - nsDependentCString(kTableEntries)); + rv = state->BindUTF8StringByName("sql"_ns, nsDependentCString(kTableEntries)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3186,8 +3162,7 @@ nsresult RewriteEntriesSchema(mozIStorageConnection* aConn) { return rv; } - rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA writable_schema = OFF")); + rv = aConn->ExecuteSimpleSQL("PRAGMA writable_schema = OFF"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3260,7 +3235,7 @@ nsresult MigrateFrom15To16(mozIStorageConnection* aConn, bool& aRewriteSchema) { // we need to apply the default "follow" to existing records in the table. // We don't actually want to keep the default in the schema for future // INSERTs. - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE entries " "ADD COLUMN request_redirect INTEGER NOT NULL DEFAULT 0")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3289,7 +3264,7 @@ nsresult MigrateFrom16To17(mozIStorageConnection* aConn, bool& aRewriteSchema) { // one. // Create a new_entries table with the new fields as of version 17. - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE new_entries (" "id INTEGER NOT NULL PRIMARY KEY, " "request_method TEXT NOT NULL, " @@ -3321,68 +3296,67 @@ nsresult MigrateFrom16To17(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Copy all of the data to the newly created table. rv = - aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("INSERT INTO new_entries (" - "id, " - "request_method, " - "request_url_no_query, " - "request_url_no_query_hash, " - "request_url_query, " - "request_url_query_hash, " - "request_referrer, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_body_id, " - "response_type, " - "response_url, " - "response_status, " - "response_status_text, " - "response_headers_guard, " - "response_body_id, " - "response_security_info_id, " - "response_principal_info, " - "cache_id " - ") SELECT " - "id, " - "request_method, " - "request_url_no_query, " - "request_url_no_query_hash, " - "request_url_query, " - "request_url_query_hash, " - "request_referrer, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_body_id, " - "response_type, " - "response_url, " - "response_status, " - "response_status_text, " - "response_headers_guard, " - "response_body_id, " - "response_security_info_id, " - "response_principal_info, " - "cache_id " - "FROM entries;")); + aConn->ExecuteSimpleSQL(nsLiteralCString("INSERT INTO new_entries (" + "id, " + "request_method, " + "request_url_no_query, " + "request_url_no_query_hash, " + "request_url_query, " + "request_url_query_hash, " + "request_referrer, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_body_id, " + "response_type, " + "response_url, " + "response_status, " + "response_status_text, " + "response_headers_guard, " + "response_body_id, " + "response_security_info_id, " + "response_principal_info, " + "cache_id " + ") SELECT " + "id, " + "request_method, " + "request_url_no_query, " + "request_url_no_query_hash, " + "request_url_query, " + "request_url_query_hash, " + "request_referrer, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_body_id, " + "response_type, " + "response_url, " + "response_status, " + "response_status_text, " + "response_headers_guard, " + "response_body_id, " + "response_security_info_id, " + "response_principal_info, " + "cache_id " + "FROM entries;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Remove the old table. - rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE entries;")); + rv = aConn->ExecuteSimpleSQL("DROP TABLE entries;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename new_entries to entries. - rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE new_entries RENAME to entries;")); + rv = aConn->ExecuteSimpleSQL("ALTER TABLE new_entries RENAME to entries;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3396,7 +3370,7 @@ nsresult MigrateFrom16To17(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Revalidate the foreign key constraints, and ensure that there are no // violations. nsCOMPtr state; - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA foreign_key_check;"), + rv = aConn->CreateStatement("PRAGMA foreign_key_check;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3433,8 +3407,8 @@ nsresult MigrateFrom17To18(mozIStorageConnection* aConn, bool& aRewriteSchema) { static_assert(int(RequestCache::Default) == 0, "This is where the 0 below comes from!"); nsresult rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE entries SET request_cache = 0 " - "WHERE request_cache = 5;")); + nsLiteralCString("UPDATE entries SET request_cache = 0 " + "WHERE request_cache = 5;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3462,7 +3436,7 @@ nsresult MigrateFrom18To19(mozIStorageConnection* aConn, bool& aRewriteSchema) { int(nsIContentPolicy::TYPE_REFRESH) == 8 && int(RequestMode::Navigate) == 3, "This is where the numbers below come from!"); - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE entries SET request_mode = 3 " "WHERE request_contentpolicytype IN (6, 7, 28, 29, 8);")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3486,7 +3460,7 @@ nsresult MigrateFrom19To20(mozIStorageConnection* aConn, bool& aRewriteSchema) { // because its required by ALTER TABLE and we need to apply the default // "no-referrer-when-downgrade" to existing records in the table. We don't // actually want to keep the default in the schema for future INSERTs. - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE entries " "ADD COLUMN request_referrer_policy INTEGER NOT NULL DEFAULT 2")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3515,7 +3489,7 @@ nsresult MigrateFrom20To21(mozIStorageConnection* aConn, bool& aRewriteSchema) { // the old one. // Create a new_entries table with the new fields as of version 21. - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE new_entries (" "id INTEGER NOT NULL PRIMARY KEY, " "request_method TEXT NOT NULL, " @@ -3546,7 +3520,7 @@ nsresult MigrateFrom20To21(mozIStorageConnection* aConn, bool& aRewriteSchema) { } // Create a response_url_list table with the new fields as of version 21. - rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE response_url_list (" "url TEXT NOT NULL, " "entry_id INTEGER NOT NULL REFERENCES entries(id) ON DELETE CASCADE" @@ -3557,81 +3531,80 @@ nsresult MigrateFrom20To21(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Copy all of the data to the newly created entries table. rv = - aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("INSERT INTO new_entries (" - "id, " - "request_method, " - "request_url_no_query, " - "request_url_no_query_hash, " - "request_url_query, " - "request_url_query_hash, " - "request_referrer, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_referrer_policy, " - "request_body_id, " - "response_type, " - "response_status, " - "response_status_text, " - "response_headers_guard, " - "response_body_id, " - "response_security_info_id, " - "response_principal_info, " - "cache_id " - ") SELECT " - "id, " - "request_method, " - "request_url_no_query, " - "request_url_no_query_hash, " - "request_url_query, " - "request_url_query_hash, " - "request_referrer, " - "request_headers_guard, " - "request_mode, " - "request_credentials, " - "request_contentpolicytype, " - "request_cache, " - "request_redirect, " - "request_referrer_policy, " - "request_body_id, " - "response_type, " - "response_status, " - "response_status_text, " - "response_headers_guard, " - "response_body_id, " - "response_security_info_id, " - "response_principal_info, " - "cache_id " - "FROM entries;")); + aConn->ExecuteSimpleSQL(nsLiteralCString("INSERT INTO new_entries (" + "id, " + "request_method, " + "request_url_no_query, " + "request_url_no_query_hash, " + "request_url_query, " + "request_url_query_hash, " + "request_referrer, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_referrer_policy, " + "request_body_id, " + "response_type, " + "response_status, " + "response_status_text, " + "response_headers_guard, " + "response_body_id, " + "response_security_info_id, " + "response_principal_info, " + "cache_id " + ") SELECT " + "id, " + "request_method, " + "request_url_no_query, " + "request_url_no_query_hash, " + "request_url_query, " + "request_url_query_hash, " + "request_referrer, " + "request_headers_guard, " + "request_mode, " + "request_credentials, " + "request_contentpolicytype, " + "request_cache, " + "request_redirect, " + "request_referrer_policy, " + "request_body_id, " + "response_type, " + "response_status, " + "response_status_text, " + "response_headers_guard, " + "response_body_id, " + "response_security_info_id, " + "response_principal_info, " + "cache_id " + "FROM entries;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Copy reponse_url to the newly created response_url_list table. - rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO response_url_list (" - "url, " - "entry_id " - ") SELECT " - "response_url, " - "id " - "FROM entries;")); + rv = + aConn->ExecuteSimpleSQL(nsLiteralCString("INSERT INTO response_url_list (" + "url, " + "entry_id " + ") SELECT " + "response_url, " + "id " + "FROM entries;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Remove the old table. - rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE entries;")); + rv = aConn->ExecuteSimpleSQL("DROP TABLE entries;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Rename new_entries to entries. - rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE new_entries RENAME to entries;")); + rv = aConn->ExecuteSimpleSQL("ALTER TABLE new_entries RENAME to entries;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3645,7 +3618,7 @@ nsresult MigrateFrom20To21(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Revalidate the foreign key constraints, and ensure that there are no // violations. nsCOMPtr state; - rv = aConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA foreign_key_check;"), + rv = aConn->CreateStatement("PRAGMA foreign_key_check;"_ns, getter_AddRefs(state)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3676,8 +3649,8 @@ nsresult MigrateFrom21To22(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Add the request_integrity column. nsresult rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE entries " - "ADD COLUMN request_integrity TEXT NULL")); + nsLiteralCString("ALTER TABLE entries " + "ADD COLUMN request_integrity TEXT NULL")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3710,7 +3683,7 @@ nsresult MigrateFrom23To24(mozIStorageConnection* aConn, bool& aRewriteSchema) { MOZ_DIAGNOSTIC_ASSERT(aConn); // Add the request_url_fragment column. - nsresult rv = aConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE entries " "ADD COLUMN request_url_fragment TEXT NOT NULL DEFAULT ''")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3746,16 +3719,16 @@ nsresult MigrateFrom25To26(mozIStorageConnection* aConn, bool& aRewriteSchema) { // Add the response_padding_size column. // Note: only opaque repsonse should be non-null interger. nsresult rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE entries " - "ADD COLUMN response_padding_size INTEGER NULL ")); + nsLiteralCString("ALTER TABLE entries " + "ADD COLUMN response_padding_size INTEGER NULL ")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE entries SET response_padding_size = 0 " - "WHERE response_type = 4" // opaque response - )); + nsLiteralCString("UPDATE entries SET response_padding_size = 0 " + "WHERE response_type = 4" // opaque response + )); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/cache/FileUtils.cpp b/dom/cache/FileUtils.cpp index 421b3a5f6174..142921af91fb 100644 --- a/dom/cache/FileUtils.cpp +++ b/dom/cache/FileUtils.cpp @@ -71,7 +71,7 @@ nsresult BodyCreateDir(nsIFile* aBaseDir) { return rv; } - rv = aBodyDir->Append(NS_LITERAL_STRING("morgue")); + rv = aBodyDir->Append(u"morgue"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -97,7 +97,7 @@ nsresult BodyDeleteDir(const QuotaInfo& aQuotaInfo, nsIFile* aBaseDir) { return rv; } - rv = aBodyDir->Append(NS_LITERAL_STRING("morgue")); + rv = aBodyDir->Append(u"morgue"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -124,7 +124,7 @@ nsresult BodyGetCacheDir(nsIFile* aBaseDir, const nsID& aId, } MOZ_DIAGNOSTIC_ASSERT(*aCacheDirOut); - rv = (*aCacheDirOut)->Append(NS_LITERAL_STRING("morgue")); + rv = (*aCacheDirOut)->Append(u"morgue"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -507,7 +507,7 @@ nsresult BodyDeleteOrphanedFiles(const QuotaInfo& aQuotaInfo, nsIFile* aBaseDir, } // Add the root morgue directory - rv = dir->Append(NS_LITERAL_STRING("morgue")); + rv = dir->Append(u"morgue"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -585,12 +585,12 @@ nsresult GetMarkerFileHandle(const QuotaInfo& aQuotaInfo, nsIFile** aFileOut) { return rv; } - rv = marker->Append(NS_LITERAL_STRING("cache")); + rv = marker->Append(u"cache"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = marker->Append(NS_LITERAL_STRING("context_open.marker")); + rv = marker->Append(u"context_open.marker"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/cache/FileUtilsImpl.h b/dom/cache/FileUtilsImpl.h index 2167bd9ba5af..49b5c81da1d0 100644 --- a/dom/cache/FileUtilsImpl.h +++ b/dom/cache/FileUtilsImpl.h @@ -30,8 +30,7 @@ nsresult BodyTraverseFiles(const QuotaInfo& aQuotaInfo, nsIFile* aBodyDir, rv = parentFile->GetNativeLeafName(nativeLeafName); MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv)); - MOZ_DIAGNOSTIC_ASSERT( - StringEndsWith(nativeLeafName, NS_LITERAL_CSTRING("morgue"))); + MOZ_DIAGNOSTIC_ASSERT(StringEndsWith(nativeLeafName, "morgue"_ns)); #endif nsCOMPtr entries; @@ -66,15 +65,14 @@ nsresult BodyTraverseFiles(const QuotaInfo& aQuotaInfo, nsIFile* aBodyDir, // Delete all tmp files regardless of known bodies. These are all // considered orphans. - if (StringEndsWith(leafName, NS_LITERAL_CSTRING(".tmp"))) { + if (StringEndsWith(leafName, ".tmp"_ns)) { if (aCanRemoveFiles) { DebugOnly result = RemoveNsIFile(aQuotaInfo, file, aTrackQuota); MOZ_ASSERT(NS_SUCCEEDED(result)); continue; } - } else if (NS_WARN_IF( - !StringEndsWith(leafName, NS_LITERAL_CSTRING(".final")))) { + } else if (NS_WARN_IF(!StringEndsWith(leafName, ".final"_ns))) { // Otherwise, it must be a .final file. If its not, then try to remove it // and move on DebugOnly result = diff --git a/dom/cache/Manager.cpp b/dom/cache/Manager.cpp index 7be040a0794b..caba217936ed 100644 --- a/dom/cache/Manager.cpp +++ b/dom/cache/Manager.cpp @@ -190,7 +190,7 @@ class DeleteOrphanedBodyAction final : public Action { return; } - rv = dbDir->Append(NS_LITERAL_STRING("cache")); + rv = dbDir->Append(u"cache"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { aResolver->Resolve(rv); return; diff --git a/dom/cache/QuotaClient.cpp b/dom/cache/QuotaClient.cpp index 831e823b3420..2e797e477937 100644 --- a/dom/cache/QuotaClient.cpp +++ b/dom/cache/QuotaClient.cpp @@ -485,8 +485,7 @@ Result CacheQuotaClient::GetUsageForOriginInternal( // Ignore transient sqlite files and marker files if (leafName.EqualsLiteral("caches.sqlite-journal") || leafName.EqualsLiteral("caches.sqlite-shm") || - leafName.Find(NS_LITERAL_CSTRING("caches.sqlite-mj"), false, 0, 0) == - 0 || + leafName.Find("caches.sqlite-mj"_ns, false, 0, 0) == 0 || leafName.EqualsLiteral("context_open.marker")) { continue; } diff --git a/dom/cache/TypeUtils.cpp b/dom/cache/TypeUtils.cpp index d4c68b822cff..52d933ae6b25 100644 --- a/dom/cache/TypeUtils.cpp +++ b/dom/cache/TypeUtils.cpp @@ -45,7 +45,7 @@ namespace { static bool HasVaryStar(mozilla::dom::InternalHeaders* aHeaders) { nsCString varyHeaders; ErrorResult rv; - aHeaders->Get(NS_LITERAL_CSTRING("vary"), varyHeaders, rv); + aHeaders->Get("vary"_ns, varyHeaders, rv); MOZ_ALWAYS_TRUE(!rv.Failed()); char* rawBuffer = varyHeaders.BeginWriting(); @@ -247,7 +247,7 @@ void TypeUtils::ToCacheQueryParams(CacheQueryParams& aOut, if (aOut.cacheNameSet()) { aOut.cacheName() = aIn.mCacheName.Value(); } else { - aOut.cacheName() = NS_LITERAL_STRING(""); + aOut.cacheName() = u""_ns; } } diff --git a/dom/canvas/CanvasRenderingContext2D.cpp b/dom/canvas/CanvasRenderingContext2D.cpp index 5436abdb2115..69ef553b6a91 100644 --- a/dom/canvas/CanvasRenderingContext2D.cpp +++ b/dom/canvas/CanvasRenderingContext2D.cpp @@ -2204,7 +2204,7 @@ static already_AddRefed CreateDeclarationForServo( // From canvas spec, force to set line-height property to 'normal' font // property. if (aProperty == eCSSProperty_font) { - const nsCString normalString = NS_LITERAL_CSTRING("normal"); + const nsCString normalString = "normal"_ns; Servo_DeclarationBlock_SetPropertyById( servoDeclarations, eCSSProperty_line_height, &normalString, false, data, ParsingMode::Default, aDocument->GetCompatibilityMode(), @@ -2252,7 +2252,7 @@ static already_AddRefed GetFontStyleForServo( } } else { RefPtr declarations = - CreateFontDeclarationForServo(NS_LITERAL_STRING("10px sans-serif"), + CreateFontDeclarationForServo(u"10px sans-serif"_ns, aPresShell->GetDocument()); MOZ_ASSERT(declarations); diff --git a/dom/canvas/CanvasUtils.cpp b/dom/canvas/CanvasUtils.cpp index 3f82312026df..854ca1a7b6ff 100644 --- a/dom/canvas/CanvasUtils.cpp +++ b/dom/canvas/CanvasUtils.cpp @@ -38,7 +38,7 @@ #define TOPIC_CANVAS_PERMISSIONS_PROMPT "canvas-permissions-prompt" #define TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER \ "canvas-permissions-prompt-hide-doorhanger" -#define PERMISSION_CANVAS_EXTRACT_DATA NS_LITERAL_CSTRING("canvas") +#define PERMISSION_CANVAS_EXTRACT_DATA "canvas"_ns using namespace mozilla::gfx; @@ -108,8 +108,7 @@ bool IsImageExtractionAllowed(Document* aDocument, JSContext* aCx, message.AppendPrintf("Blocked third party %s from extracting canvas data.", docURISpec.get()); nsContentUtils::ReportToConsoleNonLocalized( - message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"), - aDocument); + message, nsIScriptError::warningFlag, "Security"_ns, aDocument); return false; } @@ -149,8 +148,7 @@ bool IsImageExtractionAllowed(Document* aDocument, JSContext* aCx, "detected.", docURISpec.get()); nsContentUtils::ReportToConsoleNonLocalized( - message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"), - aDocument); + message, nsIScriptError::warningFlag, "Security"_ns, aDocument); } else { // It was in response to user input, so log and display the prompt. nsAutoString message; @@ -158,8 +156,7 @@ bool IsImageExtractionAllowed(Document* aDocument, JSContext* aCx, "Blocked %s from extracting canvas data, but prompting the user.", docURISpec.get()); nsContentUtils::ReportToConsoleNonLocalized( - message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"), - aDocument); + message, nsIScriptError::warningFlag, "Security"_ns, aDocument); } // Prompt the user (asynchronous). diff --git a/dom/canvas/ClientWebGLContext.cpp b/dom/canvas/ClientWebGLContext.cpp index 4c550d599e36..159ee1ae57f5 100644 --- a/dom/canvas/ClientWebGLContext.cpp +++ b/dom/canvas/ClientWebGLContext.cpp @@ -212,8 +212,7 @@ void ClientWebGLContext::OnContextLoss(const webgl::ContextLossReason reason) { void ClientWebGLContext::Event_webglcontextlost() { WEBGL_BRIDGE_LOGD("[%p] Posting webglcontextlost event", this); - const bool useDefaultHandler = - DispatchEvent(NS_LITERAL_STRING("webglcontextlost")); + const bool useDefaultHandler = DispatchEvent(u"webglcontextlost"_ns); if (useDefaultHandler) { mLossStatus = webgl::LossStatus::LostForever; } @@ -262,7 +261,7 @@ void ClientWebGLContext::Event_webglcontextrestored() { } WEBGL_BRIDGE_LOGD("[%p] Posting webglcontextrestored event", this); - (void)DispatchEvent(NS_LITERAL_STRING("webglcontextrestored")); + (void)DispatchEvent(u"webglcontextrestored"_ns); } // --------- @@ -281,7 +280,7 @@ void ClientWebGLContext::ThrowEvent_WebGLContextCreationError( } WEBGL_BRIDGE_LOGD("[%p] Posting webglcontextcreationerror event", this); - const auto kEventName = NS_LITERAL_STRING("webglcontextcreationerror"); + const auto kEventName = u"webglcontextcreationerror"_ns; dom::WebGLContextEventInit eventInit; // eventInit.mCancelable = true; // The spec says this, but it's silly. @@ -4618,9 +4617,9 @@ void ClientWebGLContext::GetSupportedProfilesASTC( const auto& limits = Limits(); auto& retarr = retval.SetValue(); - retarr.AppendElement(NS_LITERAL_STRING("ldr")); + retarr.AppendElement(u"ldr"_ns); if (limits.astcHdr) { - retarr.AppendElement(NS_LITERAL_STRING("hdr")); + retarr.AppendElement(u"hdr"_ns); } } diff --git a/dom/canvas/ImageBitmap.cpp b/dom/canvas/ImageBitmap.cpp index 89d033a50380..30c5bbe184e1 100644 --- a/dom/canvas/ImageBitmap.cpp +++ b/dom/canvas/ImageBitmap.cpp @@ -373,7 +373,7 @@ class CreateImageFromRawDataInMainThreadSyncTask final const Maybe& aCropRect, layers::Image** aImage) : WorkerMainThreadRunnable( GetCurrentThreadWorkerPrivate(), - NS_LITERAL_CSTRING("ImageBitmap :: Create Image from Raw Data")), + "ImageBitmap :: Create Image from Raw Data"_ns), mImage(aImage), mBuffer(aBuffer), mBufferLength(aBufferLength), diff --git a/dom/canvas/QueueParamTraits.h b/dom/canvas/QueueParamTraits.h index 9746ca178450..038624e2a6d4 100644 --- a/dom/canvas/QueueParamTraits.h +++ b/dom/canvas/QueueParamTraits.h @@ -397,14 +397,12 @@ struct EnumSerializer { DataType value; if (!aConsumerView.ReadParam(&value)) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IPCReadErrorReason, - NS_LITERAL_CSTRING("Bad iter")); + CrashReporter::Annotation::IPCReadErrorReason, "Bad iter"_ns); return aConsumerView.GetStatus(); } if (!EnumValidator::IsLegalValue(ParamType(value))) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IPCReadErrorReason, - NS_LITERAL_CSTRING("Illegal value")); + CrashReporter::Annotation::IPCReadErrorReason, "Illegal value"_ns); return aConsumerView.GetStatus(); } diff --git a/dom/canvas/WebGLContext.cpp b/dom/canvas/WebGLContext.cpp index a2b42adc32dc..0acaa9a71bdf 100644 --- a/dom/canvas/WebGLContext.cpp +++ b/dom/canvas/WebGLContext.cpp @@ -560,7 +560,7 @@ UniquePtr WebGLContext::CreateFormatUsage( RefPtr WebGLContext::Create(HostWebGLContext& host, const webgl::InitContextDesc& desc, webgl::InitContextResult* const out) { - nsCString failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_UNKOWN"); + nsCString failureId = "FEATURE_FAILURE_WEBGL_UNKOWN"_ns; const bool forceEnabled = StaticPrefs::webgl_force_enabled(); ScopedGfxFeatureReporter reporter("WebGL", forceEnabled); @@ -572,9 +572,9 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, if (disabled) { if (gfxPlatform::InSafeMode()) { - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_SAFEMODE"); + failureId = "FEATURE_FAILURE_WEBGL_SAFEMODE"_ns; } else { - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_DISABLED"); + failureId = "FEATURE_FAILURE_WEBGL_DISABLED"_ns; } return Err("WebGL is currently disabled."); } @@ -582,7 +582,7 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, if (desc.options.failIfMajorPerformanceCaveat) { nsCOMPtr gfxInfo = services::GetGfxInfo(); if (!HasAcceleratedLayers(gfxInfo)) { - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_PERF_CAVEAT"); + failureId = "FEATURE_FAILURE_WEBGL_PERF_CAVEAT"_ns; return Err( "failIfMajorPerformanceCaveat: Compositor is not" " hardware-accelerated."); @@ -605,9 +605,8 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, for (const auto& cur : failReasons) { // Don't try to accumulate using an empty key if |cur.key| is empty. if (cur.key.IsEmpty()) { - Telemetry::Accumulate( - Telemetry::CANVAS_WEBGL_FAILURE_ID, - NS_LITERAL_CSTRING("FEATURE_FAILURE_REASON_UNKNOWN")); + Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_FAILURE_ID, + "FEATURE_FAILURE_REASON_UNKNOWN"_ns); } else { Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_FAILURE_ID, cur.key); } @@ -615,14 +614,14 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, text.AppendLiteral("\n* "); text.Append(cur.info); } - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_REASON"); + failureId = "FEATURE_FAILURE_REASON"_ns; return Err(text.BeginReading()); } MOZ_ASSERT(webgl->gl); if (desc.options.failIfMajorPerformanceCaveat) { if (webgl->gl->IsWARP()) { - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_PERF_WARP"); + failureId = "FEATURE_FAILURE_WEBGL_PERF_WARP"_ns; return Err( "failIfMajorPerformanceCaveat: Driver is not" " hardware-accelerated."); @@ -631,7 +630,7 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, #ifdef XP_WIN if (webgl->gl->GetContextType() == gl::GLContextType::WGL && !gl::sWGLLib.HasDXInterop2()) { - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_DXGL_INTEROP2"); + failureId = "FEATURE_FAILURE_WEBGL_DXGL_INTEROP2"_ns; return Err("Caveat: WGL without DXGLInterop2."); } #endif @@ -643,14 +642,14 @@ RefPtr WebGLContext::Create(HostWebGLContext& host, if (!webgl->EnsureDefaultFB()) { MOZ_ASSERT(!webgl->mDefaultFB); MOZ_ASSERT(webgl->IsContextLost()); - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBGL_BACKBUFFER"); + failureId = "FEATURE_FAILURE_WEBGL_BACKBUFFER"_ns; return Err("Initializing WebGL backbuffer failed."); } return webgl; }(); if (res.isOk()) { - failureId = NS_LITERAL_CSTRING("SUCCESS"); + failureId = "SUCCESS"_ns; } Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_FAILURE_ID, failureId); diff --git a/dom/canvas/XRWebGLLayer.cpp b/dom/canvas/XRWebGLLayer.cpp index cefa34b02645..42c3d4260be2 100644 --- a/dom/canvas/XRWebGLLayer.cpp +++ b/dom/canvas/XRWebGLLayer.cpp @@ -110,25 +110,25 @@ already_AddRefed XRWebGLLayer::Constructor( const auto document = gl->GetParentObject()->OwnerDoc(); if (aXRWebGLLayerInitDict.mAlpha) { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING("XRWebGLLayer doesn't support no alpha value. " - "Alpha will be enabled."), - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), document); + u"XRWebGLLayer doesn't support no alpha value. " + "Alpha will be enabled."_ns, + nsIScriptError::warningFlag, "DOM"_ns, document); } if (aXRWebGLLayerInitDict.mDepth != aXRWebGLLayerInitDict.mStencil) { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING( - "XRWebGLLayer doesn't support separate " + nsLiteralString( + u"XRWebGLLayer doesn't support separate " "depth or stencil buffers. They will be enabled together."), - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), document); + nsIScriptError::warningFlag, "DOM"_ns, document); } bool antialias = aXRWebGLLayerInitDict.mAntialias; if (antialias && !StaticPrefs::webgl_msaa_force()) { antialias = false; nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING("XRWebGLLayer antialiasing is not supported." - "Antialiasing will be disabled."), - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), document); + u"XRWebGLLayer antialiasing is not supported." + "Antialiasing will be disabled."_ns, + nsIScriptError::warningFlag, "DOM"_ns, document); } webgl::OpaqueFramebufferOptions options; diff --git a/dom/clients/manager/ClientManagerService.cpp b/dom/clients/manager/ClientManagerService.cpp index 303a027d80d0..ded4ddd16342 100644 --- a/dom/clients/manager/ClientManagerService.cpp +++ b/dom/clients/manager/ClientManagerService.cpp @@ -48,8 +48,8 @@ class ClientShutdownBlocker final : public nsIAsyncShutdownBlocker { NS_IMETHOD GetName(nsAString& aNameOut) override { - aNameOut = NS_LITERAL_STRING( - "ClientManagerService: start destroying IPC actors early"); + aNameOut = nsLiteralString( + u"ClientManagerService: start destroying IPC actors early"); return NS_OK; } @@ -91,9 +91,9 @@ RefPtr OnShutdown() { nsCOMPtr blocker = new ClientShutdownBlocker(ref); - nsresult rv = phase->AddBlocker( - blocker, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("ClientManagerService shutdown")); + nsresult rv = + phase->AddBlocker(blocker, NS_LITERAL_STRING(__FILE__), __LINE__, + u"ClientManagerService shutdown"_ns); if (NS_FAILED(rv)) { ref->Resolve(true, __func__); diff --git a/dom/clients/manager/ClientSource.cpp b/dom/clients/manager/ClientSource.cpp index 88a98986a134..b3626c9f65e2 100644 --- a/dom/clients/manager/ClientSource.cpp +++ b/dom/clients/manager/ClientSource.cpp @@ -212,10 +212,9 @@ void ClientSource::WorkerExecutionReady(WorkerPrivate* aWorkerPrivate) { // execution ready. We can't reliably determine what our storage policy // is before execution ready, unfortunately. if (mController.isSome()) { - MOZ_DIAGNOSTIC_ASSERT(aWorkerPrivate->StorageAccess() > - StorageAccess::ePrivateBrowsing || - StringBeginsWith(aWorkerPrivate->ScriptURL(), - NS_LITERAL_STRING("blob:"))); + MOZ_DIAGNOSTIC_ASSERT( + aWorkerPrivate->StorageAccess() > StorageAccess::ePrivateBrowsing || + StringBeginsWith(aWorkerPrivate->ScriptURL(), u"blob:"_ns)); } // Its safe to store the WorkerPrivate* here because the ClientSource @@ -263,7 +262,7 @@ nsresult ClientSource::WindowExecutionReady(nsPIDOMWindowInner* aInnerWindow) { // assertion in this corner case. if (mController.isSome()) { MOZ_ASSERT(spec.LowerCaseEqualsLiteral("about:blank") || - StringBeginsWith(spec, NS_LITERAL_CSTRING("blob:")) || + StringBeginsWith(spec, "blob:"_ns) || StorageAllowedForWindow(aInnerWindow) == StorageAccess::eAllow); } @@ -325,8 +324,7 @@ nsresult ClientSource::DocShellExecutionReady(nsIDocShell* aDocShell) { // nsDocShell::Destroy() deletes the ClientSource. mOwner = AsVariant(nsCOMPtr(aDocShell)); - ClientSourceExecutionReadyArgs args(NS_LITERAL_CSTRING("about:blank"), - frameType); + ClientSourceExecutionReadyArgs args("about:blank"_ns, frameType); ExecutionReady(args); return NS_OK; @@ -382,15 +380,14 @@ void ClientSource::SetController( // service workers from their parent. This basically means blob: URLs // and about:blank windows. if (GetInnerWindow()) { - MOZ_DIAGNOSTIC_ASSERT( - Info().URL().LowerCaseEqualsLiteral("about:blank") || - StringBeginsWith(Info().URL(), NS_LITERAL_CSTRING("blob:")) || - StorageAllowedForWindow(GetInnerWindow()) == StorageAccess::eAllow); + MOZ_DIAGNOSTIC_ASSERT(Info().URL().LowerCaseEqualsLiteral("about:blank") || + StringBeginsWith(Info().URL(), "blob:"_ns) || + StorageAllowedForWindow(GetInnerWindow()) == + StorageAccess::eAllow); } else if (GetWorkerPrivate()) { - MOZ_DIAGNOSTIC_ASSERT(GetWorkerPrivate()->StorageAccess() > - StorageAccess::ePrivateBrowsing || - StringBeginsWith(GetWorkerPrivate()->ScriptURL(), - NS_LITERAL_STRING("blob:"))); + MOZ_DIAGNOSTIC_ASSERT( + GetWorkerPrivate()->StorageAccess() > StorageAccess::ePrivateBrowsing || + StringBeginsWith(GetWorkerPrivate()->ScriptURL(), u"blob:"_ns)); } if (mController.isSome() && mController.ref() == aServiceWorker) { @@ -438,14 +435,13 @@ RefPtr ClientSource::Control( // Local URL windows and windows with access to storage can be controlled. controlAllowed = Info().URL().LowerCaseEqualsLiteral("about:blank") || - StringBeginsWith(Info().URL(), NS_LITERAL_CSTRING("blob:")) || + StringBeginsWith(Info().URL(), "blob:"_ns) || StorageAllowedForWindow(GetInnerWindow()) == StorageAccess::eAllow; } else if (GetWorkerPrivate()) { // Local URL workers and workers with access to storage cna be controlled. controlAllowed = GetWorkerPrivate()->StorageAccess() > StorageAccess::ePrivateBrowsing || - StringBeginsWith(GetWorkerPrivate()->ScriptURL(), - NS_LITERAL_STRING("blob:")); + StringBeginsWith(GetWorkerPrivate()->ScriptURL(), u"blob:"_ns); } if (NS_WARN_IF(!controlAllowed)) { diff --git a/dom/console/Console.cpp b/dom/console/Console.cpp index ea122f53fae1..80480dddf9e8 100644 --- a/dom/console/Console.cpp +++ b/dom/console/Console.cpp @@ -680,14 +680,14 @@ class ConsoleCallDataWorkerRunnable final : public ConsoleWorkerRunnable { nsString id = frame.mFilename; nsString innerID; if (aWorkerPrivate->IsSharedWorker()) { - innerID = NS_LITERAL_STRING("SharedWorker"); + innerID = u"SharedWorker"_ns; } else if (aWorkerPrivate->IsServiceWorker()) { - innerID = NS_LITERAL_STRING("ServiceWorker"); + innerID = u"ServiceWorker"_ns; // Use scope as ID so the webconsole can decide if the message should // show up per tab CopyASCIItoUTF16(aWorkerPrivate->ServiceWorkerScope(), id); } else { - innerID = NS_LITERAL_STRING("Worker"); + innerID = u"Worker"_ns; } mCallData->SetIDs(id, innerID); @@ -1004,32 +1004,30 @@ METHOD(GroupCollapsed, "groupCollapsed") /* static */ void Console::Clear(const GlobalObject& aGlobal) { const Sequence data; - Method(aGlobal, MethodClear, NS_LITERAL_STRING("clear"), data); + Method(aGlobal, MethodClear, u"clear"_ns, data); } /* static */ void Console::GroupEnd(const GlobalObject& aGlobal) { const Sequence data; - Method(aGlobal, MethodGroupEnd, NS_LITERAL_STRING("groupEnd"), data); + Method(aGlobal, MethodGroupEnd, u"groupEnd"_ns, data); } /* static */ void Console::Time(const GlobalObject& aGlobal, const nsAString& aLabel) { - StringMethod(aGlobal, aLabel, Sequence(), MethodTime, - NS_LITERAL_STRING("time")); + StringMethod(aGlobal, aLabel, Sequence(), MethodTime, u"time"_ns); } /* static */ void Console::TimeEnd(const GlobalObject& aGlobal, const nsAString& aLabel) { StringMethod(aGlobal, aLabel, Sequence(), MethodTimeEnd, - NS_LITERAL_STRING("timeEnd")); + u"timeEnd"_ns); } /* static */ void Console::TimeLog(const GlobalObject& aGlobal, const nsAString& aLabel, const Sequence& aData) { - StringMethod(aGlobal, aLabel, aData, MethodTimeLog, - NS_LITERAL_STRING("timeLog")); + StringMethod(aGlobal, aLabel, aData, MethodTimeLog, u"timeLog"_ns); } /* static */ @@ -1087,20 +1085,19 @@ void Console::TimeStamp(const GlobalObject& aGlobal, return; } - Method(aGlobal, MethodTimeStamp, NS_LITERAL_STRING("timeStamp"), data); + Method(aGlobal, MethodTimeStamp, u"timeStamp"_ns, data); } /* static */ void Console::Profile(const GlobalObject& aGlobal, const Sequence& aData) { - ProfileMethod(aGlobal, MethodProfile, NS_LITERAL_STRING("profile"), aData); + ProfileMethod(aGlobal, MethodProfile, u"profile"_ns, aData); } /* static */ void Console::ProfileEnd(const GlobalObject& aGlobal, const Sequence& aData) { - ProfileMethod(aGlobal, MethodProfileEnd, NS_LITERAL_STRING("profileEnd"), - aData); + ProfileMethod(aGlobal, MethodProfileEnd, u"profileEnd"_ns, aData); } /* static */ @@ -1213,20 +1210,20 @@ void Console::ProfileMethodMainthread(JSContext* aCx, const nsAString& aAction, void Console::Assert(const GlobalObject& aGlobal, bool aCondition, const Sequence& aData) { if (!aCondition) { - Method(aGlobal, MethodAssert, NS_LITERAL_STRING("assert"), aData); + Method(aGlobal, MethodAssert, u"assert"_ns, aData); } } /* static */ void Console::Count(const GlobalObject& aGlobal, const nsAString& aLabel) { StringMethod(aGlobal, aLabel, Sequence(), MethodCount, - NS_LITERAL_STRING("count")); + u"count"_ns); } /* static */ void Console::CountReset(const GlobalObject& aGlobal, const nsAString& aLabel) { StringMethod(aGlobal, aLabel, Sequence(), MethodCountReset, - NS_LITERAL_STRING("countReset")); + u"countReset"_ns); } namespace { @@ -1426,14 +1423,14 @@ void Console::MethodInternal(JSContext* aCx, MethodName aMethodName, if (mInnerID) { callData->SetIDs(mOuterID, mInnerID); } else if (!mPassedInnerID.IsEmpty()) { - callData->SetIDs(NS_LITERAL_STRING("jsm"), mPassedInnerID); + callData->SetIDs(u"jsm"_ns, mPassedInnerID); } else { nsAutoString filename; if (callData->mTopStackFrame.isSome()) { filename = callData->mTopStackFrame->mFilename; } - callData->SetIDs(NS_LITERAL_STRING("jsm"), filename); + callData->SetIDs(u"jsm"_ns, filename); } GetOrCreateMainThreadData()->ProcessCallData(aCx, callData, aData); diff --git a/dom/console/ConsoleInstance.cpp b/dom/console/ConsoleInstance.cpp index f5a4fca51689..b5c443717507 100644 --- a/dom/console/ConsoleInstance.cpp +++ b/dom/console/ConsoleInstance.cpp @@ -134,28 +134,26 @@ METHOD(GroupCollapsed, "groupCollapsed") void ConsoleInstance::GroupEnd(JSContext* aCx) { const Sequence data; RefPtr console(mConsole); - console->MethodInternal(aCx, Console::MethodGroupEnd, - NS_LITERAL_STRING("groupEnd"), data); + console->MethodInternal(aCx, Console::MethodGroupEnd, u"groupEnd"_ns, data); } void ConsoleInstance::Time(JSContext* aCx, const nsAString& aLabel) { RefPtr console(mConsole); console->StringMethodInternal(aCx, aLabel, Sequence(), - Console::MethodTime, NS_LITERAL_STRING("time")); + Console::MethodTime, u"time"_ns); } void ConsoleInstance::TimeLog(JSContext* aCx, const nsAString& aLabel, const Sequence& aData) { RefPtr console(mConsole); console->StringMethodInternal(aCx, aLabel, aData, Console::MethodTimeLog, - NS_LITERAL_STRING("timeLog")); + u"timeLog"_ns); } void ConsoleInstance::TimeEnd(JSContext* aCx, const nsAString& aLabel) { RefPtr console(mConsole); console->StringMethodInternal(aCx, aLabel, Sequence(), - Console::MethodTimeEnd, - NS_LITERAL_STRING("timeEnd")); + Console::MethodTimeEnd, u"timeEnd"_ns); } void ConsoleInstance::TimeStamp(JSContext* aCx, @@ -170,52 +168,47 @@ void ConsoleInstance::TimeStamp(JSContext* aCx, } RefPtr console(mConsole); - console->MethodInternal(aCx, Console::MethodTimeStamp, - NS_LITERAL_STRING("timeStamp"), data); + console->MethodInternal(aCx, Console::MethodTimeStamp, u"timeStamp"_ns, data); } void ConsoleInstance::Profile(JSContext* aCx, const Sequence& aData) { RefPtr console(mConsole); - console->ProfileMethodInternal(aCx, Console::MethodProfile, - NS_LITERAL_STRING("profile"), aData); + console->ProfileMethodInternal(aCx, Console::MethodProfile, u"profile"_ns, + aData); } void ConsoleInstance::ProfileEnd(JSContext* aCx, const Sequence& aData) { RefPtr console(mConsole); console->ProfileMethodInternal(aCx, Console::MethodProfileEnd, - NS_LITERAL_STRING("profileEnd"), aData); + u"profileEnd"_ns, aData); } void ConsoleInstance::Assert(JSContext* aCx, bool aCondition, const Sequence& aData) { if (!aCondition) { RefPtr console(mConsole); - console->MethodInternal(aCx, Console::MethodAssert, - NS_LITERAL_STRING("assert"), aData); + console->MethodInternal(aCx, Console::MethodAssert, u"assert"_ns, aData); } } void ConsoleInstance::Count(JSContext* aCx, const nsAString& aLabel) { RefPtr console(mConsole); console->StringMethodInternal(aCx, aLabel, Sequence(), - Console::MethodCount, - NS_LITERAL_STRING("count")); + Console::MethodCount, u"count"_ns); } void ConsoleInstance::CountReset(JSContext* aCx, const nsAString& aLabel) { RefPtr console(mConsole); console->StringMethodInternal(aCx, aLabel, Sequence(), - Console::MethodCountReset, - NS_LITERAL_STRING("countReset")); + Console::MethodCountReset, u"countReset"_ns); } void ConsoleInstance::Clear(JSContext* aCx) { const Sequence data; RefPtr console(mConsole); - console->MethodInternal(aCx, Console::MethodClear, NS_LITERAL_STRING("clear"), - data); + console->MethodInternal(aCx, Console::MethodClear, u"clear"_ns, data); } void ConsoleInstance::ReportForServiceWorkerScope(const nsAString& aScope, diff --git a/dom/console/ConsoleUtils.cpp b/dom/console/ConsoleUtils.cpp index 7cc5ebb8208e..4c4179319bd6 100644 --- a/dom/console/ConsoleUtils.cpp +++ b/dom/console/ConsoleUtils.cpp @@ -81,19 +81,19 @@ void ConsoleUtils::ReportForServiceWorkerScopeInternal( event.mID.Value().SetAsString() = aScope; event.mInnerID.Construct(); - event.mInnerID.Value().SetAsString() = NS_LITERAL_STRING("ServiceWorker"); + event.mInnerID.Value().SetAsString() = u"ServiceWorker"_ns; switch (aLevel) { case eLog: - event.mLevel = NS_LITERAL_STRING("log"); + event.mLevel = u"log"_ns; break; case eWarning: - event.mLevel = NS_LITERAL_STRING("warn"); + event.mLevel = u"warn"_ns; break; case eError: - event.mLevel = NS_LITERAL_STRING("error"); + event.mLevel = u"error"_ns; break; } @@ -131,7 +131,7 @@ void ConsoleUtils::ReportForServiceWorkerScopeInternal( return; } - storage->RecordEvent(NS_LITERAL_STRING("ServiceWorker"), aScope, eventValue); + storage->RecordEvent(u"ServiceWorker"_ns, aScope, eventValue); } JSObject* ConsoleUtils::GetOrCreateSandbox(JSContext* aCx) { diff --git a/dom/events/ContentEventHandler.cpp b/dom/events/ContentEventHandler.cpp index 74e512c15088..cdaa18c349c8 100644 --- a/dom/events/ContentEventHandler.cpp +++ b/dom/events/ContentEventHandler.cpp @@ -506,7 +506,7 @@ static bool IsPaddingBR(nsIContent* aContent) { static void ConvertToNativeNewlines(nsString& aString) { #if defined(XP_WIN) - aString.ReplaceSubstring(NS_LITERAL_STRING("\n"), NS_LITERAL_STRING("\r\n")); + aString.ReplaceSubstring(u"\n"_ns, u"\r\n"_ns); #endif } diff --git a/dom/events/DataTransfer.cpp b/dom/events/DataTransfer.cpp index 4c623a240af2..f9a66d75a286 100644 --- a/dom/events/DataTransfer.cpp +++ b/dom/events/DataTransfer.cpp @@ -190,8 +190,8 @@ DataTransfer::DataTransfer(nsISupports* aParent, EventMessage aEventMessage, RefPtr variant = new nsVariantCC(); variant->SetAsAString(aString); - DebugOnly rvIgnored = SetDataWithPrincipal( - NS_LITERAL_STRING("text/plain"), variant, 0, sysPrincipal, false); + DebugOnly rvIgnored = + SetDataWithPrincipal(u"text/plain"_ns, variant, 0, sysPrincipal, false); NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored), "Failed to set given string to the DataTransfer object"); } @@ -472,7 +472,7 @@ already_AddRefed DataTransfer::MozTypesAt( } if (addFile) { - types->Add(NS_LITERAL_STRING("Files")); + types->Add(u"Files"_ns); } } @@ -581,7 +581,7 @@ bool DataTransfer::PrincipalMaySetData(const nsAString& aType, // pass to WebExtensions. auto principal = BasePrincipal::Cast(aPrincipal); if (!principal->AddonPolicy() && - StringBeginsWith(aType, NS_LITERAL_STRING("text/x-moz-place"))) { + StringBeginsWith(aType, u"text/x-moz-place"_ns)) { NS_WARNING("Disallowing adding moz-place types to DataTransfer"); return false; } @@ -674,9 +674,9 @@ void DataTransfer::GetExternalTransferableFormats( aTransferable->FlavorsTransferableCanExport(flavors); if (aPlainTextOnly) { - auto index = flavors.IndexOf(NS_LITERAL_CSTRING(kUnicodeMime)); + auto index = flavors.IndexOf(nsLiteralCString(kUnicodeMime)); if (index != flavors.NoIndex) { - aResult->AppendElement(NS_LITERAL_CSTRING(kUnicodeMime)); + aResult->AppendElement(nsLiteralCString(kUnicodeMime)); } return; } @@ -1300,9 +1300,8 @@ nsresult DataTransfer::CacheExternalData(const char* aFormat, uint32_t aIndex, RefPtr item; if (strcmp(aFormat, kUnicodeMime) == 0) { - item = - mItems->SetDataWithPrincipal(NS_LITERAL_STRING("text/plain"), nullptr, - aIndex, aPrincipal, false, aHidden, rv); + item = mItems->SetDataWithPrincipal(u"text/plain"_ns, nullptr, aIndex, + aPrincipal, false, aHidden, rv); if (NS_WARN_IF(rv.Failed())) { return rv.StealNSResult(); } @@ -1310,9 +1309,8 @@ nsresult DataTransfer::CacheExternalData(const char* aFormat, uint32_t aIndex, } if (strcmp(aFormat, kURLDataMime) == 0) { - item = mItems->SetDataWithPrincipal(NS_LITERAL_STRING("text/uri-list"), - nullptr, aIndex, aPrincipal, false, - aHidden, rv); + item = mItems->SetDataWithPrincipal(u"text/uri-list"_ns, nullptr, aIndex, + aPrincipal, false, aHidden, rv); if (NS_WARN_IF(rv.Failed())) { return rv.StealNSResult(); } diff --git a/dom/events/DataTransferItem.h b/dom/events/DataTransferItem.h index e15c5b675911..f80b358493cc 100644 --- a/dom/events/DataTransferItem.h +++ b/dom/events/DataTransferItem.h @@ -55,13 +55,13 @@ class DataTransferItem final : public nsISupports, public nsWrapperCache { void GetKind(nsAString& aKind) const { switch (mKind) { case KIND_FILE: - aKind = NS_LITERAL_STRING("file"); + aKind = u"file"_ns; return; case KIND_STRING: - aKind = NS_LITERAL_STRING("string"); + aKind = u"string"_ns; return; default: - aKind = NS_LITERAL_STRING("other"); + aKind = u"other"_ns; return; } } diff --git a/dom/events/DataTransferItemList.cpp b/dom/events/DataTransferItemList.cpp index 840ece75ae8d..ee0bab49f617 100644 --- a/dom/events/DataTransferItemList.cpp +++ b/dom/events/DataTransferItemList.cpp @@ -447,7 +447,7 @@ void DataTransferItemList::GetTypes(nsTArray& aTypes, } if (foundFile) { - aTypes.AppendElement(NS_LITERAL_STRING("Files")); + aTypes.AppendElement(u"Files"_ns); } } diff --git a/dom/events/Event.cpp b/dom/events/Event.cpp index 48894110a7e3..6c386d2e7d72 100644 --- a/dom/events/Event.cpp +++ b/dom/events/Event.cpp @@ -431,8 +431,7 @@ void Event::SetEventType(const nsAString& aEventTypeArg) { aEventTypeArg, mEvent->mClass, &(mEvent->mMessage)); mEvent->SetDefaultComposed(); } else { - mEvent->mSpecifiedEventType = - NS_Atomize(NS_LITERAL_STRING("on") + aEventTypeArg); + mEvent->mSpecifiedEventType = NS_Atomize(u"on"_ns + aEventTypeArg); mEvent->mMessage = eUnidentifiedEvent; mEvent->SetComposed(aEventTypeArg); } @@ -739,7 +738,7 @@ double Event::TimeStamp() { void Event::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) { if (aSerializeInterfaceType) { - IPC::WriteParam(aMsg, NS_LITERAL_STRING("event")); + IPC::WriteParam(aMsg, u"event"_ns); } nsString type; diff --git a/dom/events/EventListenerManager.cpp b/dom/events/EventListenerManager.cpp index 122dd6e3bd10..5f3ce198b7cf 100644 --- a/dom/events/EventListenerManager.cpp +++ b/dom/events/EventListenerManager.cpp @@ -953,7 +953,7 @@ nsresult EventListenerManager::CompileEventHandlerInternal( } aListener = nullptr; - nsAutoCString url(NS_LITERAL_CSTRING("-moz-evil:lying-event-listener")); + nsAutoCString url("-moz-evil:lying-event-listener"_ns); MOZ_ASSERT(body); MOZ_ASSERT(aElement); nsIURI* uri = aElement->OwnerDoc()->GetDocumentURI(); @@ -1134,7 +1134,7 @@ EventMessage EventListenerManager::GetEventMessageAndAtomForListener( return nsContentUtils::GetEventMessageAndAtomForListener(aType, aAtom); } - *aAtom = NS_Atomize(NS_LITERAL_STRING("on") + aType).take(); + *aAtom = NS_Atomize(u"on"_ns + aType).take(); return eUnidentifiedEvent; } @@ -1471,7 +1471,7 @@ uint32_t EventListenerManager::MutationListenerBits() { } bool EventListenerManager::HasListenersFor(const nsAString& aEventName) const { - RefPtr atom = NS_Atomize(NS_LITERAL_STRING("on") + aEventName); + RefPtr atom = NS_Atomize(u"on"_ns + aEventName); return HasListenersFor(atom); } @@ -1480,7 +1480,7 @@ bool EventListenerManager::HasListenersFor(nsAtom* aEventNameWithOn) const { nsAutoString name; aEventNameWithOn->ToString(name); #endif - NS_ASSERTION(StringBeginsWith(name, NS_LITERAL_STRING("on")), + NS_ASSERTION(StringBeginsWith(name, u"on"_ns), "Event name does not start with 'on'"); uint32_t count = mListeners.Length(); for (uint32_t i = 0; i < count; ++i) { diff --git a/dom/events/EventTarget.cpp b/dom/events/EventTarget.cpp index 7b7997cdb0d9..e792b61d9c19 100644 --- a/dom/events/EventTarget.cpp +++ b/dom/events/EventTarget.cpp @@ -142,7 +142,7 @@ EventHandlerNonNull* EventTarget::GetEventHandler(nsAtom* aType) { void EventTarget::SetEventHandler(const nsAString& aType, EventHandlerNonNull* aHandler, ErrorResult& aRv) { - if (!StringBeginsWith(aType, NS_LITERAL_STRING("on"))) { + if (!StringBeginsWith(aType, u"on"_ns)) { aRv.Throw(NS_ERROR_INVALID_ARG); return; } diff --git a/dom/events/GlobalKeyListener.cpp b/dom/events/GlobalKeyListener.cpp index 50cc1298b3d0..b0046d6229bc 100644 --- a/dom/events/GlobalKeyListener.cpp +++ b/dom/events/GlobalKeyListener.cpp @@ -108,94 +108,84 @@ void GlobalKeyListener::InstallKeyboardEventListenersTo( // For marking each keyboard event as if it's reserved by chrome, // GlobalKeyListeners need to listen each keyboard events before // web contents. - aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtCapture()); - aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtCapture()); - aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtCapture()); - aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), TrustedEventsAtCapture()); - aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), TrustedEventsAtCapture()); + aEventListenerManager->AddEventListenerByType(this, u"keydown"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->AddEventListenerByType(this, u"keyup"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->AddEventListenerByType(this, u"keypress"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->AddEventListenerByType(this, u"mozkeydownonplugin"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->AddEventListenerByType(this, u"mozkeyuponplugin"_ns, + TrustedEventsAtCapture()); // For reducing the IPC cost, preventing to dispatch reserved keyboard // events into the content process. aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupCapture()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupCapture()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupCapture()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), - TrustedEventsAtSystemGroupCapture()); + this, u"mozkeydownonplugin"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), - TrustedEventsAtSystemGroupCapture()); + this, u"mozkeyuponplugin"_ns, TrustedEventsAtSystemGroupCapture()); // Handle keyboard events in bubbling phase of the system event group. aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupBubble()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupBubble()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupBubble()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); // mozaccesskeynotfound event is fired when modifiers of keypress event // matches with modifier of content access key but it's not consumed by // remote content. aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozaccesskeynotfound"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozaccesskeynotfound"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozkeydownonplugin"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozkeyuponplugin"_ns, TrustedEventsAtSystemGroupBubble()); } void GlobalKeyListener::RemoveKeyboardEventListenersFrom( EventListenerManager* aEventListenerManager) { + aEventListenerManager->RemoveEventListenerByType(this, u"keydown"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->RemoveEventListenerByType(this, u"keyup"_ns, + TrustedEventsAtCapture()); + aEventListenerManager->RemoveEventListenerByType(this, u"keypress"_ns, + TrustedEventsAtCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtCapture()); - aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtCapture()); - aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtCapture()); - aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), TrustedEventsAtCapture()); - aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), TrustedEventsAtCapture()); + this, u"mozkeydownonplugin"_ns, TrustedEventsAtCapture()); + aEventListenerManager->RemoveEventListenerByType(this, u"mozkeyuponplugin"_ns, + TrustedEventsAtCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupCapture()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupCapture()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupCapture()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), - TrustedEventsAtSystemGroupCapture()); + this, u"mozkeydownonplugin"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), - TrustedEventsAtSystemGroupCapture()); + this, u"mozkeyuponplugin"_ns, TrustedEventsAtSystemGroupCapture()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupBubble()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupBubble()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupBubble()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozaccesskeynotfound"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozaccesskeynotfound"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeydownonplugin"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozkeydownonplugin"_ns, TrustedEventsAtSystemGroupBubble()); aEventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mozkeyuponplugin"), - TrustedEventsAtSystemGroupBubble()); + this, u"mozkeyuponplugin"_ns, TrustedEventsAtSystemGroupBubble()); } NS_IMETHODIMP diff --git a/dom/events/KeyEventHandler.cpp b/dom/events/KeyEventHandler.cpp index 0f52a463e0f9..5abbb05a3db9 100644 --- a/dom/events/KeyEventHandler.cpp +++ b/dom/events/KeyEventHandler.cpp @@ -677,7 +677,7 @@ void KeyEventHandler::ReportKeyConflict(const char16_t* aKey, params.AppendElement(aModifiers); params.AppendElement(id); nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Key Event Handler"), doc, + "Key Event Handler"_ns, doc, nsContentUtils::eDOM_PROPERTIES, aMessageName, params, nullptr, EmptyString(), 0); } diff --git a/dom/events/NotifyPaintEvent.cpp b/dom/events/NotifyPaintEvent.cpp index c3afbef261e1..c9f5f31feea6 100644 --- a/dom/events/NotifyPaintEvent.cpp +++ b/dom/events/NotifyPaintEvent.cpp @@ -83,7 +83,7 @@ already_AddRefed NotifyPaintEvent::PaintRequests( void NotifyPaintEvent::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) { if (aSerializeInterfaceType) { - IPC::WriteParam(aMsg, NS_LITERAL_STRING("notifypaintevent")); + IPC::WriteParam(aMsg, u"notifypaintevent"_ns); } Event::Serialize(aMsg, false); diff --git a/dom/events/PendingFullscreenEvent.h b/dom/events/PendingFullscreenEvent.h index 022cf4ad3780..68cafd3dd165 100644 --- a/dom/events/PendingFullscreenEvent.h +++ b/dom/events/PendingFullscreenEvent.h @@ -43,10 +43,10 @@ class PendingFullscreenEvent { nsString name; switch (mType) { case FullscreenEventType::Change: - name = NS_LITERAL_STRING("fullscreenchange"); + name = u"fullscreenchange"_ns; break; case FullscreenEventType::Error: - name = NS_LITERAL_STRING("fullscreenerror"); + name = u"fullscreenerror"_ns; break; } nsINode* target = mTarget->GetComposedDoc() == mDocument ? mTarget.get() diff --git a/dom/events/PointerEventHandler.cpp b/dom/events/PointerEventHandler.cpp index a8b062f4e87a..b129426e0353 100644 --- a/dom/events/PointerEventHandler.cpp +++ b/dom/events/PointerEventHandler.cpp @@ -645,8 +645,8 @@ void PointerEventHandler::DispatchGotOrLostPointerCaptureEvent( ConvertPointerTypeToString(aPointerEvent->mInputSource, init.mPointerType); init.mIsPrimary = aPointerEvent->mIsPrimary; RefPtr event; - event = PointerEvent::Constructor( - aCaptureTarget, NS_LITERAL_STRING("lostpointercapture"), init); + event = PointerEvent::Constructor(aCaptureTarget, u"lostpointercapture"_ns, + init); targetDoc->DispatchEvent(*event); return; } diff --git a/dom/events/ScrollAreaEvent.cpp b/dom/events/ScrollAreaEvent.cpp index f48a7d71767f..4f40176582f5 100644 --- a/dom/events/ScrollAreaEvent.cpp +++ b/dom/events/ScrollAreaEvent.cpp @@ -42,7 +42,7 @@ void ScrollAreaEvent::InitScrollAreaEvent(const nsAString& aEventType, void ScrollAreaEvent::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) { if (aSerializeInterfaceType) { - IPC::WriteParam(aMsg, NS_LITERAL_STRING("scrollareaevent")); + IPC::WriteParam(aMsg, u"scrollareaevent"_ns); } Event::Serialize(aMsg, false); diff --git a/dom/events/TextComposition.cpp b/dom/events/TextComposition.cpp index 23c238017a31..0d167c2fda1d 100644 --- a/dom/events/TextComposition.cpp +++ b/dom/events/TextComposition.cpp @@ -43,7 +43,7 @@ using namespace mozilla::widget; namespace mozilla { -#define IDEOGRAPHIC_SPACE (NS_LITERAL_STRING(u"\x3000")) +#define IDEOGRAPHIC_SPACE (u"\x3000"_ns) /****************************************************************************** * TextComposition diff --git a/dom/events/UIEvent.cpp b/dom/events/UIEvent.cpp index 9af26363f03a..e394d7c5a150 100644 --- a/dom/events/UIEvent.cpp +++ b/dom/events/UIEvent.cpp @@ -208,7 +208,7 @@ void UIEvent::DuplicatePrivateData() { void UIEvent::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) { if (aSerializeInterfaceType) { - IPC::WriteParam(aMsg, NS_LITERAL_STRING("uievent")); + IPC::WriteParam(aMsg, u"uievent"_ns); } Event::Serialize(aMsg, false); diff --git a/dom/events/WheelHandlingHelper.cpp b/dom/events/WheelHandlingHelper.cpp index 2d40a9108582..672927cf8eeb 100644 --- a/dom/events/WheelHandlingHelper.cpp +++ b/dom/events/WheelHandlingHelper.cpp @@ -302,8 +302,7 @@ void WheelTransaction::OnFailToScrollTarget() { // This event is used for automated tests, see bug 442774. nsContentUtils::DispatchEventOnlyToChrome( sTargetFrame->GetContent()->OwnerDoc(), sTargetFrame->GetContent(), - NS_LITERAL_STRING("MozMouseScrollFailed"), CanBubble::eYes, - Cancelable::eYes); + u"MozMouseScrollFailed"_ns, CanBubble::eYes, Cancelable::eYes); } // The target frame might be destroyed in the event handler, at that time, // we need to finish the current transaction @@ -329,7 +328,7 @@ void WheelTransaction::OnTimeout(nsITimer* aTimer, void* aClosure) { // This event is used for automated tests, see bug 442774. nsContentUtils::DispatchEventOnlyToChrome( frame->GetContent()->OwnerDoc(), frame->GetContent(), - NS_LITERAL_STRING("MozMouseScrollTransactionTimeout"), CanBubble::eYes, + u"MozMouseScrollTransactionTimeout"_ns, CanBubble::eYes, Cancelable::eYes); } } diff --git a/dom/fetch/BodyExtractor.cpp b/dom/fetch/BodyExtractor.cpp index 5e4954059b28..655236049cd3 100644 --- a/dom/fetch/BodyExtractor.cpp +++ b/dom/fetch/BodyExtractor.cpp @@ -102,8 +102,7 @@ nsresult BodyExtractor::GetAsStream( // Make sure to use the encoding we'll send ErrorResult res; - serializer->SerializeToStream(*mBody, output, NS_LITERAL_STRING("UTF-8"), - res); + serializer->SerializeToStream(*mBody, output, u"UTF-8"_ns, res); if (NS_WARN_IF(res.Failed())) { return res.StealNSResult(); } diff --git a/dom/fetch/Fetch.cpp b/dom/fetch/Fetch.cpp index 283894c76a3a..fd0e4f353527 100644 --- a/dom/fetch/Fetch.cpp +++ b/dom/fetch/Fetch.cpp @@ -1233,7 +1233,7 @@ void FetchBody::SetMimeType() { ErrorResult result; nsCString contentTypeValues; MOZ_ASSERT(DerivedClass()->GetInternalHeaders()); - DerivedClass()->GetInternalHeaders()->Get(NS_LITERAL_CSTRING("Content-Type"), + DerivedClass()->GetInternalHeaders()->Get("Content-Type"_ns, contentTypeValues, result); MOZ_ALWAYS_TRUE(!result.Failed()); diff --git a/dom/fetch/FetchDriver.cpp b/dom/fetch/FetchDriver.cpp index 3c5a554d1212..dca82809aeab 100644 --- a/dom/fetch/FetchDriver.cpp +++ b/dom/fetch/FetchDriver.cpp @@ -727,7 +727,7 @@ nsresult FetchDriver::HttpFetch( // Set the initiator type nsCOMPtr timedChannel(do_QueryInterface(httpChan)); if (timedChannel) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("fetch")); + timedChannel->SetInitiatorType(u"fetch"_ns); } } @@ -738,8 +738,7 @@ nsresult FetchDriver::HttpFetch( if (uploadChan) { nsAutoCString contentType; ErrorResult result; - mRequest->Headers()->GetFirst(NS_LITERAL_CSTRING("content-type"), - contentType, result); + mRequest->Headers()->GetFirst("content-type"_ns, contentType, result); // We don't actually expect "result" to have failed here: that only happens // for invalid header names. But if for some reason it did, just propagate // it out. @@ -751,7 +750,7 @@ nsresult FetchDriver::HttpFetch( // void string if no header was set. #ifdef DEBUG bool hasContentTypeHeader = - mRequest->Headers()->Has(NS_LITERAL_CSTRING("content-type"), result); + mRequest->Headers()->Has("content-type"_ns, result); MOZ_ASSERT(!result.Failed()); MOZ_ASSERT_IF(!hasContentTypeHeader, contentType.IsVoid()); #endif // DEBUG @@ -816,9 +815,9 @@ nsresult FetchDriver::HttpFetch( if (mRequest->GetIntegrity().IsEmpty()) { nsCOMPtr cic = do_QueryInterface(chan); if (cic) { - cic->PreferAlternativeDataType( - NS_LITERAL_CSTRING(WASM_ALT_DATA_TYPE_V1), - NS_LITERAL_CSTRING(WASM_CONTENT_TYPE), false); + cic->PreferAlternativeDataType(nsLiteralCString(WASM_ALT_DATA_TYPE_V1), + nsLiteralCString(WASM_CONTENT_TYPE), + false); } } @@ -982,10 +981,8 @@ FetchDriver::OnStartRequest(nsIRequest* aRequest) { // Content-Length (which refer to the decoded data) is obscured behind the // encodings. ErrorResult result; - if (response->Headers()->Has(NS_LITERAL_CSTRING("content-encoding"), - result) || - response->Headers()->Has(NS_LITERAL_CSTRING("transfer-encoding"), - result)) { + if (response->Headers()->Has("content-encoding"_ns, result) || + response->Headers()->Has("transfer-encoding"_ns, result)) { // We cannot trust the content-length when content-encoding or // transfer-encoding are set. There are many servers which just // get this wrong. @@ -993,19 +990,18 @@ FetchDriver::OnStartRequest(nsIRequest* aRequest) { } MOZ_ASSERT(!result.Failed()); } else { - response = new InternalResponse(200, NS_LITERAL_CSTRING("OK"), - mRequest->GetCredentialsMode()); + response = + new InternalResponse(200, "OK"_ns, mRequest->GetCredentialsMode()); if (!contentType.IsEmpty()) { nsAutoCString contentCharset; channel->GetContentCharset(contentCharset); if (NS_SUCCEEDED(rv) && !contentCharset.IsEmpty()) { - contentType += NS_LITERAL_CSTRING(";charset=") + contentCharset; + contentType += ";charset="_ns + contentCharset; } IgnoredErrorResult result; - response->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), - contentType, result); + response->Headers()->Append("Content-Type"_ns, contentType, result); MOZ_ASSERT(!result.Failed()); } @@ -1014,8 +1010,7 @@ FetchDriver::OnStartRequest(nsIRequest* aRequest) { contentLenStr.AppendInt(contentLength); IgnoredErrorResult result; - response->Headers()->Append(NS_LITERAL_CSTRING("Content-Length"), - contentLenStr, result); + response->Headers()->Append("Content-Length"_ns, contentLenStr, result); MOZ_ASSERT(!result.Failed()); } } diff --git a/dom/fetch/FetchObserver.cpp b/dom/fetch/FetchObserver.cpp index 0808968be762..70d3deef2057 100644 --- a/dom/fetch/FetchObserver.cpp +++ b/dom/fetch/FetchObserver.cpp @@ -72,8 +72,7 @@ void FetchObserver::SetState(FetchState aState) { // TODO which kind of event should we dispatch here? - RefPtr event = - Event::Constructor(this, NS_LITERAL_STRING("statechange"), init); + RefPtr event = Event::Constructor(this, u"statechange"_ns, init); event->SetTrusted(true); DispatchEvent(*event); diff --git a/dom/fetch/FetchStreamReader.cpp b/dom/fetch/FetchStreamReader.cpp index f1cd4b8790aa..00a52c94d01b 100644 --- a/dom/fetch/FetchStreamReader.cpp +++ b/dom/fetch/FetchStreamReader.cpp @@ -344,11 +344,10 @@ void FetchStreamReader::ReportErrorToConsole(JSContext* aCx, params.AppendElement(valueString); RefPtr reporter = new ConsoleReportCollector(); - reporter->AddConsoleReport( - nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("ReadableStreamReader.read"), - nsContentUtils::eDOM_PROPERTIES, sourceSpec, line, column, - NS_LITERAL_CSTRING("ReadableStreamReadingFailed"), params); + reporter->AddConsoleReport(nsIScriptError::errorFlag, + "ReadableStreamReader.read"_ns, + nsContentUtils::eDOM_PROPERTIES, sourceSpec, line, + column, "ReadableStreamReadingFailed"_ns, params); uint64_t innerWindowId = 0; diff --git a/dom/fetch/FetchUtil.cpp b/dom/fetch/FetchUtil.cpp index 24640f1b6691..cbc3e5231bb9 100644 --- a/dom/fetch/FetchUtil.cpp +++ b/dom/fetch/FetchUtil.cpp @@ -49,7 +49,7 @@ nsresult FetchUtil::GetValidRequestMethod(const nsACString& aMethod, static bool FindCRLF(nsACString::const_iterator& aStart, nsACString::const_iterator& aEnd) { nsACString::const_iterator end(aEnd); - return FindInReadable(NS_LITERAL_CSTRING("\r\n"), aStart, end); + return FindInReadable("\r\n"_ns, aStart, end); } // Reads over a CRLF and positions start after it. @@ -501,8 +501,7 @@ bool FetchUtil::StreamResponseToJS(JSContext* aCx, JS::HandleObject aObj, response->GetUrl(url); nsCString sourceMapUrl; - response->GetInternalHeaders()->Get(NS_LITERAL_CSTRING("SourceMap"), - sourceMapUrl, result); + response->GetInternalHeaders()->Get("SourceMap"_ns, sourceMapUrl, result); if (NS_WARN_IF(result.Failed())) { return ThrowException(aCx, JSMSG_ERROR_CONSUMING_RESPONSE); } diff --git a/dom/fetch/InternalHeaders.cpp b/dom/fetch/InternalHeaders.cpp index e3767f320161..5e4638f2af97 100644 --- a/dom/fetch/InternalHeaders.cpp +++ b/dom/fetch/InternalHeaders.cpp @@ -501,9 +501,9 @@ already_AddRefed InternalHeaders::BasicHeaders( ErrorResult result; // The Set-Cookie headers cannot be invalid mutable headers, so the Delete // must succeed. - basic->Delete(NS_LITERAL_CSTRING("Set-Cookie"), result); + basic->Delete("Set-Cookie"_ns, result); MOZ_ASSERT(!result.Failed()); - basic->Delete(NS_LITERAL_CSTRING("Set-Cookie2"), result); + basic->Delete("Set-Cookie2"_ns, result); MOZ_ASSERT(!result.Failed()); return basic.forget(); } @@ -515,8 +515,7 @@ already_AddRefed InternalHeaders::CORSHeaders( ErrorResult result; nsAutoCString acExposedNames; - aHeaders->Get(NS_LITERAL_CSTRING("Access-Control-Expose-Headers"), - acExposedNames, result); + aHeaders->Get("Access-Control-Expose-Headers"_ns, acExposedNames, result); MOZ_ASSERT(!result.Failed()); bool allowAllHeaders = false; diff --git a/dom/fetch/InternalResponse.h b/dom/fetch/InternalResponse.h index 6ba71e3e3151..35691c1ab826 100644 --- a/dom/fetch/InternalResponse.h +++ b/dom/fetch/InternalResponse.h @@ -124,7 +124,7 @@ class InternalResponse final { #ifdef DEBUG for (uint32_t i = 0; i < mURLList.Length(); ++i) { - MOZ_ASSERT(mURLList[i].Find(NS_LITERAL_CSTRING("#")) == kNotFound); + MOZ_ASSERT(mURLList[i].Find("#"_ns) == kNotFound); } #endif } diff --git a/dom/fetch/Request.cpp b/dom/fetch/Request.cpp index 4b1b0fcc0a7e..b9acb6662722 100644 --- a/dom/fetch/Request.cpp +++ b/dom/fetch/Request.cpp @@ -233,9 +233,8 @@ class ReferrerSameOriginChecker final : public WorkerMainThreadRunnable { public: ReferrerSameOriginChecker(WorkerPrivate* aWorkerPrivate, const nsAString& aReferrerURL, nsresult& aResult) - : WorkerMainThreadRunnable( - aWorkerPrivate, - NS_LITERAL_CSTRING("Fetch :: Referrer same origin check")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "Fetch :: Referrer same origin check"_ns), mReferrerURL(aReferrerURL), mResult(aResult) { mWorkerPrivate->AssertIsOnWorkerThread(); @@ -359,7 +358,7 @@ SafeRefPtr Request::Constructor(nsIGlobalObject* aGlobal, if (aInit.mReferrer.WasPassed()) { const nsString& referrer = aInit.mReferrer.Value(); if (referrer.IsEmpty()) { - request->SetReferrer(NS_LITERAL_STRING("")); + request->SetReferrer(u""_ns); } else { nsAutoString referrerURL; if (NS_IsMainThread()) { @@ -589,9 +588,8 @@ SafeRefPtr Request::Constructor(nsIGlobalObject* aGlobal, nsCOMPtr temporaryBody = stream; if (!contentTypeWithCharset.IsVoid() && - !requestHeaders->Has(NS_LITERAL_CSTRING("Content-Type"), aRv)) { - requestHeaders->Append(NS_LITERAL_CSTRING("Content-Type"), - contentTypeWithCharset, aRv); + !requestHeaders->Has("Content-Type"_ns, aRv)) { + requestHeaders->Append("Content-Type"_ns, contentTypeWithCharset, aRv); } if (NS_WARN_IF(aRv.Failed())) { diff --git a/dom/fetch/Response.cpp b/dom/fetch/Response.cpp index 2e3d697941ee..41f314f9afe6 100644 --- a/dom/fetch/Response.cpp +++ b/dom/fetch/Response.cpp @@ -158,8 +158,8 @@ already_AddRefed Response::Redirect(const GlobalObject& aGlobal, return nullptr; } - r->GetInternalHeaders()->Set(NS_LITERAL_CSTRING("Location"), - NS_ConvertUTF16toUTF8(parsedURL), aRv); + r->GetInternalHeaders()->Set("Location"_ns, NS_ConvertUTF16toUTF8(parsedURL), + aRv); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } @@ -354,11 +354,10 @@ already_AddRefed Response::Constructor( internalResponse->SetBody(bodyStream, bodySize); if (!contentTypeWithCharset.IsVoid() && - !internalResponse->Headers()->Has(NS_LITERAL_CSTRING("Content-Type"), - aRv)) { + !internalResponse->Headers()->Has("Content-Type"_ns, aRv)) { // Ignore Append() failing here. ErrorResult error; - internalResponse->Headers()->Append(NS_LITERAL_CSTRING("Content-Type"), + internalResponse->Headers()->Append("Content-Type"_ns, contentTypeWithCharset, error); error.SuppressException(); } diff --git a/dom/file/BaseBlobImpl.h b/dom/file/BaseBlobImpl.h index 1c8e2e1b58b8..610849b0a167 100644 --- a/dom/file/BaseBlobImpl.h +++ b/dom/file/BaseBlobImpl.h @@ -117,7 +117,7 @@ class BaseBlobImpl : public BlobImpl { virtual bool IsFile() const override { return mIsFile; } virtual void GetBlobImplType(nsAString& aBlobImplType) const override { - aBlobImplType = NS_LITERAL_STRING("BaseBlobImpl"); + aBlobImplType = u"BaseBlobImpl"_ns; } protected: diff --git a/dom/file/EmptyBlobImpl.h b/dom/file/EmptyBlobImpl.h index e4cefd8f558d..a3b46ae54b5c 100644 --- a/dom/file/EmptyBlobImpl.h +++ b/dom/file/EmptyBlobImpl.h @@ -29,7 +29,7 @@ class EmptyBlobImpl final : public BaseBlobImpl { bool IsMemoryFile() const override { return true; } void GetBlobImplType(nsAString& aBlobImplType) const override { - aBlobImplType = NS_LITERAL_STRING("EmptyBlobImpl"); + aBlobImplType = u"EmptyBlobImpl"_ns; } private: diff --git a/dom/file/FileBlobImpl.cpp b/dom/file/FileBlobImpl.cpp index aef20f7ace75..caaa0c9236b8 100644 --- a/dom/file/FileBlobImpl.cpp +++ b/dom/file/FileBlobImpl.cpp @@ -162,8 +162,7 @@ class FileBlobImpl::GetTypeRunnable final : public WorkerMainThreadRunnable { public: GetTypeRunnable(WorkerPrivate* aWorkerPrivate, FileBlobImpl* aBlobImpl, const MutexAutoLock& aProofOfLock) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("FileBlobImpl :: GetType")), + : WorkerMainThreadRunnable(aWorkerPrivate, "FileBlobImpl :: GetType"_ns), mBlobImpl(aBlobImpl), mProofOfLock(aProofOfLock) { MOZ_ASSERT(aBlobImpl); @@ -238,7 +237,7 @@ void FileBlobImpl::GetTypeInternal(nsAString& aType, } void FileBlobImpl::GetBlobImplType(nsAString& aBlobImplType) const { - aBlobImplType = NS_LITERAL_STRING("FileBlobImpl"); + aBlobImplType = u"FileBlobImpl"_ns; } int64_t FileBlobImpl::GetLastModified(ErrorResult& aRv) { diff --git a/dom/file/FileReader.cpp b/dom/file/FileReader.cpp index 220d05b64a18..4625c5ef2421 100644 --- a/dom/file/FileReader.cpp +++ b/dom/file/FileReader.cpp @@ -608,7 +608,7 @@ FileReader::Notify(nsITimer* aTimer) { mTimerIsActive = false; if (mProgressEventWasDelayed) { - rv = DispatchProgressEvent(NS_LITERAL_STRING("progress")); + rv = DispatchProgressEvent(u"progress"_ns); NS_ENSURE_SUCCESS(rv, rv); StartProgressEventTimer(); diff --git a/dom/file/MemoryBlobImpl.cpp b/dom/file/MemoryBlobImpl.cpp index 214c1814ebc8..fcb9814b9bd7 100644 --- a/dom/file/MemoryBlobImpl.cpp +++ b/dom/file/MemoryBlobImpl.cpp @@ -133,7 +133,7 @@ class MemoryBlobImplDataOwnerMemoryReporter final : public nsIMemoryReporter { } aHandleReport->Callback( - /* process */ NS_LITERAL_CSTRING(""), + /* process */ ""_ns, nsPrintfCString( "explicit/dom/memory-file-data/large/file(length=%" PRIu64 ", sha1=%s)", @@ -156,9 +156,8 @@ class MemoryBlobImplDataOwnerMemoryReporter final : public nsIMemoryReporter { if (smallObjectsTotal > 0) { aHandleReport->Callback( - /* process */ NS_LITERAL_CSTRING(""), - NS_LITERAL_CSTRING("explicit/dom/memory-file-data/small"), KIND_HEAP, - UNITS_BYTES, smallObjectsTotal, + /* process */ ""_ns, "explicit/dom/memory-file-data/small"_ns, + KIND_HEAP, UNITS_BYTES, smallObjectsTotal, nsPrintfCString( "Memory used to back small memory files (i.e. those taking up " "less " diff --git a/dom/file/MemoryBlobImpl.h b/dom/file/MemoryBlobImpl.h index 20e277259cd4..b60ed3574c7f 100644 --- a/dom/file/MemoryBlobImpl.h +++ b/dom/file/MemoryBlobImpl.h @@ -58,7 +58,7 @@ class MemoryBlobImpl final : public BaseBlobImpl { } void GetBlobImplType(nsAString& aBlobImplType) const override { - aBlobImplType = NS_LITERAL_STRING("MemoryBlobImpl"); + aBlobImplType = u"MemoryBlobImpl"_ns; } class DataOwner final : public mozilla::LinkedListElement { diff --git a/dom/file/StringBlobImpl.h b/dom/file/StringBlobImpl.h index d770c1fcf15a..38aaff7a331a 100644 --- a/dom/file/StringBlobImpl.h +++ b/dom/file/StringBlobImpl.h @@ -37,7 +37,7 @@ class StringBlobImpl final : public BaseBlobImpl, public nsIMemoryReporter { } void GetBlobImplType(nsAString& aBlobImplType) const override { - aBlobImplType = NS_LITERAL_STRING("StringBlobImpl"); + aBlobImplType = u"StringBlobImpl"_ns; } private: diff --git a/dom/file/TemporaryFileBlobImpl.h b/dom/file/TemporaryFileBlobImpl.h index ee0bca9a8d01..d5d7d0eae429 100644 --- a/dom/file/TemporaryFileBlobImpl.h +++ b/dom/file/TemporaryFileBlobImpl.h @@ -31,7 +31,7 @@ class TemporaryFileBlobImpl final : public FileBlobImpl { ErrorResult& aRv) override; void GetBlobImplType(nsAString& aBlobImplType) const override { - aBlobImplType = NS_LITERAL_STRING("TemporaryFileBlobImpl"); + aBlobImplType = u"TemporaryFileBlobImpl"_ns; } protected: diff --git a/dom/file/ipc/RemoteLazyInputStreamStorage.cpp b/dom/file/ipc/RemoteLazyInputStreamStorage.cpp index 01b80c0d6408..cec40ccb408c 100644 --- a/dom/file/ipc/RemoteLazyInputStreamStorage.cpp +++ b/dom/file/ipc/RemoteLazyInputStreamStorage.cpp @@ -69,7 +69,7 @@ RemoteLazyInputStreamStorage::Observe(nsISupports* aSubject, const char* aTopic, } uint64_t childID = CONTENT_PROCESS_ID_UNKNOWN; - props->GetPropertyAsUint64(NS_LITERAL_STRING("childID"), &childID); + props->GetPropertyAsUint64(u"childID"_ns, &childID); if (NS_WARN_IF(childID == CONTENT_PROCESS_ID_UNKNOWN)) { return NS_ERROR_FAILURE; } diff --git a/dom/file/uri/BlobURLProtocolHandler.cpp b/dom/file/uri/BlobURLProtocolHandler.cpp index ecc309b0e1f6..7e82ad13ce50 100644 --- a/dom/file/uri/BlobURLProtocolHandler.cpp +++ b/dom/file/uri/BlobURLProtocolHandler.cpp @@ -413,7 +413,7 @@ class ReleasingTimerHolder final : public Runnable, NS_ENSURE_TRUE(!!phase, NS_OK); rv = phase->AddBlocker(this, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("ReleasingTimerHolder shutdown")); + u"ReleasingTimerHolder shutdown"_ns); NS_ENSURE_SUCCESS(rv, NS_OK); raii.release(); diff --git a/dom/filehandle/ActorsParent.cpp b/dom/filehandle/ActorsParent.cpp index 68ac411a8ea6..0b6c733032ce 100644 --- a/dom/filehandle/ActorsParent.cpp +++ b/dom/filehandle/ActorsParent.cpp @@ -760,7 +760,7 @@ nsresult FileHandleThreadPool::Init() { mThreadPool = new nsThreadPool(); - nsresult rv = mThreadPool->SetName(NS_LITERAL_CSTRING("FileHandles")); + nsresult rv = mThreadPool->SetName("FileHandles"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/filesystem/FileSystemSecurity.cpp b/dom/filesystem/FileSystemSecurity.cpp index e032eda31eab..99e22ca8eaa3 100644 --- a/dom/filesystem/FileSystemSecurity.cpp +++ b/dom/filesystem/FileSystemSecurity.cpp @@ -80,13 +80,12 @@ bool FileSystemSecurity::ContentProcessHasAccessTo(ContentParentId aId, AssertIsInMainProcess(); #if defined(XP_WIN) - if (StringBeginsWith(aPath, NS_LITERAL_STRING("..\\")) || - FindInReadable(NS_LITERAL_STRING("\\..\\"), aPath)) { + if (StringBeginsWith(aPath, u"..\\"_ns) || + FindInReadable(u"\\..\\"_ns, aPath)) { return false; } #elif defined(XP_UNIX) - if (StringBeginsWith(aPath, NS_LITERAL_STRING("../")) || - FindInReadable(NS_LITERAL_STRING("/../"), aPath)) { + if (StringBeginsWith(aPath, u"../"_ns) || FindInReadable(u"/../"_ns, aPath)) { return false; } #endif diff --git a/dom/gamepad/GamepadManager.cpp b/dom/gamepad/GamepadManager.cpp index 605327b828ad..e85b0bc30e25 100644 --- a/dom/gamepad/GamepadManager.cpp +++ b/dom/gamepad/GamepadManager.cpp @@ -255,8 +255,8 @@ void GamepadManager::RemoveGamepad(uint32_t aIndex, void GamepadManager::FireButtonEvent(EventTarget* aTarget, Gamepad* aGamepad, uint32_t aButton, double aValue) { - nsString name = aValue == 1.0L ? NS_LITERAL_STRING("gamepadbuttondown") - : NS_LITERAL_STRING("gamepadbuttonup"); + nsString name = + aValue == 1.0L ? u"gamepadbuttondown"_ns : u"gamepadbuttonup"_ns; GamepadButtonEventInit init; init.mBubbles = false; init.mCancelable = false; @@ -278,8 +278,8 @@ void GamepadManager::FireAxisMoveEvent(EventTarget* aTarget, Gamepad* aGamepad, init.mGamepad = aGamepad; init.mAxis = aAxis; init.mValue = aValue; - RefPtr event = GamepadAxisMoveEvent::Constructor( - aTarget, NS_LITERAL_STRING("gamepadaxismove"), init); + RefPtr event = + GamepadAxisMoveEvent::Constructor(aTarget, u"gamepadaxismove"_ns, init); event->SetTrusted(true); @@ -365,8 +365,8 @@ void GamepadManager::NewConnectionEvent(uint32_t aIndex, bool aConnected) { void GamepadManager::FireConnectionEvent(EventTarget* aTarget, Gamepad* aGamepad, bool aConnected) { - nsString name = aConnected ? NS_LITERAL_STRING("gamepadconnected") - : NS_LITERAL_STRING("gamepaddisconnected"); + nsString name = + aConnected ? u"gamepadconnected"_ns : u"gamepaddisconnected"_ns; GamepadEventInit init; init.mBubbles = false; init.mCancelable = false; diff --git a/dom/geolocation/Geolocation.cpp b/dom/geolocation/Geolocation.cpp index 51c04d2f40f5..c5703ec9cec0 100644 --- a/dom/geolocation/Geolocation.cpp +++ b/dom/geolocation/Geolocation.cpp @@ -200,8 +200,8 @@ nsGeolocationRequest::nsGeolocationRequest( int32_t aWatchId) : ContentPermissionRequestBase( aLocator->GetPrincipal(), - ConvertWeakReferenceToWindow(aLocator->GetOwner()), - NS_LITERAL_CSTRING("geo"), NS_LITERAL_CSTRING("geolocation")), + ConvertWeakReferenceToWindow(aLocator->GetOwner()), "geo"_ns, + "geolocation"_ns), mIsWatchPositionRequest(aWatchPositionRequest), mCallback(std::move(aCallback)), mErrorCallback(std::move(aErrorCallback)), @@ -973,8 +973,7 @@ bool Geolocation::ShouldBlockInsecureRequests() const { } if (!nsGlobalWindowInner::Cast(win)->IsSecureContext()) { - nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("DOM"), doc, + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "DOM"_ns, doc, nsContentUtils::eDOM_PROPERTIES, "GeolocationInsecureRequestIsForbidden"); return true; diff --git a/dom/geolocation/GeolocationPositionError.cpp b/dom/geolocation/GeolocationPositionError.cpp index efeaaddc05a7..f4ef8d1786af 100644 --- a/dom/geolocation/GeolocationPositionError.cpp +++ b/dom/geolocation/GeolocationPositionError.cpp @@ -24,13 +24,13 @@ GeolocationPositionError::~GeolocationPositionError() = default; void GeolocationPositionError::GetMessage(nsAString& aMessage) const { switch (mCode) { case GeolocationPositionError_Binding::PERMISSION_DENIED: - aMessage = NS_LITERAL_STRING("User denied geolocation prompt"); + aMessage = u"User denied geolocation prompt"_ns; break; case GeolocationPositionError_Binding::POSITION_UNAVAILABLE: - aMessage = NS_LITERAL_STRING("Unknown error acquiring position"); + aMessage = u"Unknown error acquiring position"_ns; break; case GeolocationPositionError_Binding::TIMEOUT: - aMessage = NS_LITERAL_STRING("Position acquisition timed out"); + aMessage = u"Position acquisition timed out"_ns; break; default: break; diff --git a/dom/html/HTMLAllCollection.cpp b/dom/html/HTMLAllCollection.cpp index afc05cfd869e..6ea11201f869 100644 --- a/dom/html/HTMLAllCollection.cpp +++ b/dom/html/HTMLAllCollection.cpp @@ -69,7 +69,7 @@ void HTMLAllCollection::Item(const Optional& aNameOrIndex, nsContentList* HTMLAllCollection::Collection() { if (!mCollection) { Document* document = mDocument; - mCollection = document->GetElementsByTagName(NS_LITERAL_STRING("*")); + mCollection = document->GetElementsByTagName(u"*"_ns); MOZ_ASSERT(mCollection); } return mCollection; diff --git a/dom/html/HTMLAudioElement.cpp b/dom/html/HTMLAudioElement.cpp index 3c70f1cc3344..4b1b46e3cdd0 100644 --- a/dom/html/HTMLAudioElement.cpp +++ b/dom/html/HTMLAudioElement.cpp @@ -78,7 +78,7 @@ already_AddRefed HTMLAudioElement::Audio( RefPtr audio = static_cast(NS_NewHTMLAudioElement(nodeInfo.forget())); - audio->SetHTMLAttr(nsGkAtoms::preload, NS_LITERAL_STRING("auto"), aRv); + audio->SetHTMLAttr(nsGkAtoms::preload, u"auto"_ns, aRv); if (aRv.Failed()) { return nullptr; } @@ -99,7 +99,7 @@ nsresult HTMLAudioElement::SetAcceptHeader(nsIHttpChannel* aChannel) { "application/ogg;q=0.7," "video/*;q=0.6,*/*;q=0.5"); - return aChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), value, false); + return aChannel->SetRequestHeader("Accept"_ns, value, false); } JSObject* HTMLAudioElement::WrapNode(JSContext* aCx, diff --git a/dom/html/HTMLCanvasElement.cpp b/dom/html/HTMLCanvasElement.cpp index 3bf2d43dcf80..c30366d27a7f 100644 --- a/dom/html/HTMLCanvasElement.cpp +++ b/dom/html/HTMLCanvasElement.cpp @@ -284,8 +284,7 @@ void HTMLCanvasElementObserver::RegisterVisibilityChangeEvent() { } Document* document = mElement->OwnerDoc(); - document->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"), this, - true, false); + document->AddSystemEventListener(u"visibilitychange"_ns, this, true, false); } void HTMLCanvasElementObserver::UnregisterVisibilityChangeEvent() { @@ -294,8 +293,7 @@ void HTMLCanvasElementObserver::UnregisterVisibilityChangeEvent() { } Document* document = mElement->OwnerDoc(); - document->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"), - this, true); + document->RemoveSystemEventListener(u"visibilitychange"_ns, this, true); } void HTMLCanvasElementObserver::RegisterObserverEvents() { @@ -486,7 +484,7 @@ nsresult HTMLCanvasElement::DispatchPrintCallback(nsITimerCallback* aCallback) { if (!mCurrentContext) { nsresult rv; nsCOMPtr context; - rv = GetContext(NS_LITERAL_STRING("2d"), getter_AddRefs(context)); + rv = GetContext(u"2d"_ns, getter_AddRefs(context)); NS_ENSURE_SUCCESS(rv, rv); } mPrintState = new HTMLCanvasPrintState(this, mCurrentContext, aCallback); @@ -536,7 +534,7 @@ nsresult HTMLCanvasElement::CopyInnerTo(HTMLCanvasElement* aDest) { nsIntSize size = GetWidthHeight(); if (size.height > 0 && size.width > 0) { nsCOMPtr cxt; - aDest->GetContext(NS_LITERAL_STRING("2d"), getter_AddRefs(cxt)); + aDest->GetContext(u"2d"_ns, getter_AddRefs(cxt)); RefPtr context2d = static_cast(cxt.get()); if (context2d && !mPrintCallback) { @@ -736,7 +734,7 @@ nsresult HTMLCanvasElement::ToDataURLImpl(JSContext* aCx, nsAString& aDataURL) { nsIntSize size = GetWidthHeight(); if (size.height == 0 || size.width == 0) { - aDataURL = NS_LITERAL_STRING("data:,"); + aDataURL = u"data:,"_ns; return NS_OK; } @@ -765,7 +763,7 @@ nsresult HTMLCanvasElement::ToDataURLImpl(JSContext* aCx, NS_ENSURE_SUCCESS(rv, rv); // build data URL string - aDataURL = NS_LITERAL_STRING("data:") + type + NS_LITERAL_STRING(";base64,"); + aDataURL = u"data:"_ns + type + u";base64,"_ns; uint64_t count; rv = stream->Available(&count); diff --git a/dom/html/HTMLDetailsElement.cpp b/dom/html/HTMLDetailsElement.cpp index 16140ca9ac5a..9e82361506e0 100644 --- a/dom/html/HTMLDetailsElement.cpp +++ b/dom/html/HTMLDetailsElement.cpp @@ -49,8 +49,8 @@ nsresult HTMLDetailsElement::BeforeSetAttr(int32_t aNameSpaceID, nsAtom* aName, } // According to the html spec, a 'toggle' event is a simple event which // does not bubble. - mToggleEventDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("toggle"), CanBubble::eNo); + mToggleEventDispatcher = + new AsyncEventDispatcher(this, u"toggle"_ns, CanBubble::eNo); mToggleEventDispatcher->PostDOMEvent(); } } diff --git a/dom/html/HTMLDialogElement.cpp b/dom/html/HTMLDialogElement.cpp index c4ebc373a255..9f46099d3b9b 100644 --- a/dom/html/HTMLDialogElement.cpp +++ b/dom/html/HTMLDialogElement.cpp @@ -46,8 +46,8 @@ void HTMLDialogElement::Close( RemoveFromTopLayerIfNeeded(); - RefPtr eventDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("close"), CanBubble::eNo); + RefPtr eventDispatcher = + new AsyncEventDispatcher(this, u"close"_ns, CanBubble::eNo); eventDispatcher->PostDOMEvent(); } @@ -183,9 +183,9 @@ void HTMLDialogElement::RunCancelDialogSteps() { // 1) Let close be the result of firing an event named cancel at dialog, with // the cancelable attribute initialized to true. bool defaultAction = true; - nsContentUtils::DispatchTrustedEvent( - OwnerDoc(), this, NS_LITERAL_STRING("cancel"), CanBubble::eNo, - Cancelable::eYes, &defaultAction); + nsContentUtils::DispatchTrustedEvent(OwnerDoc(), this, u"cancel"_ns, + CanBubble::eNo, Cancelable::eYes, + &defaultAction); // 2) If close is true and dialog has an open attribute, then close the dialog // with no return value. diff --git a/dom/html/HTMLFormElement.cpp b/dom/html/HTMLFormElement.cpp index 513ee9787436..d832de8f406a 100644 --- a/dom/html/HTMLFormElement.cpp +++ b/dom/html/HTMLFormElement.cpp @@ -268,7 +268,7 @@ void HTMLFormElement::MaybeSubmit(Element* aSubmitter) { init.mSubmitter = aSubmitter ? nsGenericHTMLElement::FromNode(aSubmitter) : nullptr; RefPtr event = - SubmitEvent::Constructor(this, NS_LITERAL_STRING("submit"), init); + SubmitEvent::Constructor(this, u"submit"_ns, init); event->SetTrusted(true); nsEventStatus status = nsEventStatus_eIgnore; presShell->HandleDOMEventWithTarget(this, event, &status); @@ -981,8 +981,7 @@ nsresult HTMLFormElement::NotifySubmitObservers(nsIURI* aActionURL, bool defaultAction = true; nsresult rv = nsContentUtils::DispatchEventOnlyToChrome( OwnerDoc(), static_cast(this), - aEarlyNotify ? NS_LITERAL_STRING("DOMFormBeforeSubmit") - : NS_LITERAL_STRING("DOMFormSubmit"), + aEarlyNotify ? u"DOMFormBeforeSubmit"_ns : u"DOMFormSubmit"_ns, CanBubble::eYes, Cancelable::eYes, &defaultAction); *aCancelSubmit = !defaultAction; if (*aCancelSubmit) { @@ -1023,7 +1022,7 @@ nsresult HTMLFormElement::ConstructEntryList(FormData* aFormData) { init.mCancelable = false; init.mFormData = aFormData; RefPtr event = - FormDataEvent::Constructor(this, NS_LITERAL_STRING("formdata"), init); + FormDataEvent::Constructor(this, u"formdata"_ns, init); event->SetTrusted(true); EventDispatcher::DispatchDOMEvent(ToSupports(this), nullptr, event, nullptr, @@ -1182,8 +1181,8 @@ void HTMLFormElement::PostPasswordEvent() { } mFormPasswordEventDispatcher = - new AsyncEventDispatcher(this, NS_LITERAL_STRING("DOMFormHasPassword"), - CanBubble::eYes, ChromeOnlyDispatch::eYes); + new AsyncEventDispatcher(this, u"DOMFormHasPassword"_ns, CanBubble::eYes, + ChromeOnlyDispatch::eYes); mFormPasswordEventDispatcher->PostDOMEvent(); } @@ -1718,8 +1717,8 @@ nsresult HTMLFormElement::GetActionURL(nsIURI** aActionURL, EmptyString(), // aScriptSample 0, // aLineNumber 0, // aColumnNumber - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("upgradeInsecureRequest"), document->InnerWindowID(), + nsIScriptError::warningFlag, "upgradeInsecureRequest"_ns, + document->InnerWindowID(), !!document->NodePrincipal()->OriginAttributesRef().mPrivateBrowsingId); } @@ -1831,9 +1830,8 @@ bool HTMLFormElement::CheckFormValidity( bool defaultAction = true; nsContentUtils::DispatchTrustedEvent( sortedControls[i]->OwnerDoc(), - static_cast(sortedControls[i]), - NS_LITERAL_STRING("invalid"), CanBubble::eNo, Cancelable::eYes, - &defaultAction); + static_cast(sortedControls[i]), u"invalid"_ns, + CanBubble::eNo, Cancelable::eYes, &defaultAction); // Add all unhandled invalid controls to aInvalidElements if the caller // requested them. @@ -1930,7 +1928,7 @@ bool HTMLFormElement::CheckValidFormSubmission() { RefPtr event = NS_NewDOMCustomEvent(OwnerDoc(), nullptr, nullptr); - event->InitCustomEvent(jsapi.cx(), NS_LITERAL_STRING("MozInvalidForm"), + event->InitCustomEvent(jsapi.cx(), u"MozInvalidForm"_ns, /* CanBubble */ true, /* Cancelable */ true, detail); event->SetTrusted(true); diff --git a/dom/html/HTMLFormSubmission.cpp b/dom/html/HTMLFormSubmission.cpp index e042b212541f..634c995bfae7 100644 --- a/dom/html/HTMLFormSubmission.cpp +++ b/dom/html/HTMLFormSubmission.cpp @@ -43,9 +43,9 @@ namespace { void SendJSWarning(Document* aDocument, const char* aWarningName, const nsTArray& aWarningArgs) { - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("HTML"), aDocument, - nsContentUtils::eFORMS_PROPERTIES, aWarningName, aWarningArgs); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "HTML"_ns, + aDocument, nsContentUtils::eFORMS_PROPERTIES, + aWarningName, aWarningArgs); } void RetrieveFileName(Blob* aBlob, nsAString& aFilename) { @@ -142,10 +142,9 @@ nsresult FSURLEncoded::AddNameValuePair(const nsAString& aName, // Append data to string if (mQueryString.IsEmpty()) { - mQueryString += convName + NS_LITERAL_CSTRING("=") + convValue; + mQueryString += convName + "="_ns + convValue; } else { - mQueryString += NS_LITERAL_CSTRING("&") + convName + - NS_LITERAL_CSTRING("=") + convValue; + mQueryString += "&"_ns + convName + "="_ns + convValue; } return NS_OK; @@ -255,7 +254,7 @@ nsresult FSURLEncoded::GetEncodedSubmission(nsIURI* aURI, return NS_ERROR_OUT_OF_MEMORY; } - path += NS_LITERAL_CSTRING("&force-plain-text=Y&body=") + escapedBody; + path += "&force-plain-text=Y&body="_ns + escapedBody; return NS_MutateURI(aURI).SetPathQueryRef(path).Finalize(aOutURI); } else { @@ -288,8 +287,7 @@ nsresult FSURLEncoded::GetEncodedSubmission(nsIURI* aURI, // mQueryString is empty, nsIURI::SetQuery() will remove the query // component, which is not what we want. rv = NS_MutateURI(aURI) - .SetQuery(mQueryString.IsEmpty() ? NS_LITERAL_CSTRING("?") - : mQueryString) + .SetQuery(mQueryString.IsEmpty() ? "?"_ns : mQueryString) .Finalize(aOutURI); } else { nsAutoCString path; @@ -374,8 +372,7 @@ FSMultipartFormData::~FSMultipartFormData() { nsIInputStream* FSMultipartFormData::GetSubmissionBody( uint64_t* aContentLength) { // Finish data - mPostDataChunk += - NS_LITERAL_CSTRING("--") + mBoundary + NS_LITERAL_CSTRING("--" CRLF); + mPostDataChunk += "--"_ns + mBoundary + nsLiteralCString("--" CRLF); // Add final data input stream AddPostDataStream(); @@ -404,10 +401,10 @@ nsresult FSMultipartFormData::AddNameValuePair(const nsAString& aName, // XXX: name parameter should be encoded per RFC 2231 // RFC 2388 specifies that RFC 2047 be used, but I think it's not // consistent with MIME standard. - mPostDataChunk += - NS_LITERAL_CSTRING("--") + mBoundary + NS_LITERAL_CSTRING(CRLF) + - NS_LITERAL_CSTRING("Content-Disposition: form-data; name=\"") + nameStr + - NS_LITERAL_CSTRING("\"" CRLF CRLF) + valueStr + NS_LITERAL_CSTRING(CRLF); + mPostDataChunk += "--"_ns + mBoundary + nsLiteralCString(CRLF) + + "Content-Disposition: form-data; name=\""_ns + nameStr + + nsLiteralCString("\"" CRLF CRLF) + valueStr + + nsLiteralCString(CRLF); return NS_OK; } @@ -518,8 +515,7 @@ nsresult FSMultipartFormData::AddNameDirectoryPair(const nsAString& aName, rv = EncodeVal(dirname16, dirname, true); NS_ENSURE_SUCCESS(rv, rv); - AddDataChunk(nameStr, dirname, NS_LITERAL_CSTRING("application/octet-stream"), - nullptr, 0); + AddDataChunk(nameStr, dirname, "application/octet-stream"_ns, nullptr, 0); return NS_OK; } @@ -532,16 +528,14 @@ void FSMultipartFormData::AddDataChunk(const nsACString& aName, // Make MIME block for name/value pair // // more appropriate than always using binary? - mPostDataChunk += - NS_LITERAL_CSTRING("--") + mBoundary + NS_LITERAL_CSTRING(CRLF); + mPostDataChunk += "--"_ns + mBoundary + nsLiteralCString(CRLF); // XXX: name/filename parameter should be encoded per RFC 2231 // RFC 2388 specifies that RFC 2047 be used, but I think it's not // consistent with the MIME standard. - mPostDataChunk += - NS_LITERAL_CSTRING("Content-Disposition: form-data; name=\"") + aName + - NS_LITERAL_CSTRING("\"; filename=\"") + aFilename + - NS_LITERAL_CSTRING("\"" CRLF) + NS_LITERAL_CSTRING("Content-Type: ") + - aContentType + NS_LITERAL_CSTRING(CRLF CRLF); + mPostDataChunk += "Content-Disposition: form-data; name=\""_ns + aName + + "\"; filename=\""_ns + aFilename + + nsLiteralCString("\"" CRLF) + "Content-Type: "_ns + + aContentType + nsLiteralCString(CRLF CRLF); // We should not try to append an invalid stream. That will happen for example // if we try to update a file that actually do not exist. @@ -629,8 +623,7 @@ nsresult FSTextPlain::AddNameValuePair(const nsAString& aName, // XXX This won't work well with a name like "a=b" or "a\nb" but I suppose // text/plain doesn't care about that. Parsers aren't built for escaped // values so we'll have to live with it. - mBody.Append(aName + NS_LITERAL_STRING("=") + aValue + - NS_LITERAL_STRING(CRLF)); + mBody.Append(aName + u"="_ns + aValue + NS_LITERAL_STRING(CRLF)); return NS_OK; } @@ -676,7 +669,7 @@ nsresult FSTextPlain::GetEncodedSubmission(nsIURI* aURI, return NS_ERROR_OUT_OF_MEMORY; } - path += NS_LITERAL_CSTRING("&force-plain-text=Y&body=") + escapedBody; + path += "&force-plain-text=Y&body="_ns + escapedBody; rv = NS_MutateURI(aURI).SetPathQueryRef(path).Finalize(aOutURI); } else { @@ -745,7 +738,7 @@ nsresult EncodingFormSubmission::EncodeVal(const nsAString& aStr, aOut.Adopt(nsLinebreakConverter::ConvertLineBreaks( aOut.get(), nsLinebreakConverter::eLinebreakAny, nsLinebreakConverter::eLinebreakSpace)); - aOut.ReplaceSubstring(NS_LITERAL_CSTRING("\""), NS_LITERAL_CSTRING("\\\"")); + aOut.ReplaceSubstring("\""_ns, "\\\""_ns); } return NS_OK; diff --git a/dom/html/HTMLFormSubmission.h b/dom/html/HTMLFormSubmission.h index 2add139e544e..67217e28edf2 100644 --- a/dom/html/HTMLFormSubmission.h +++ b/dom/html/HTMLFormSubmission.h @@ -239,8 +239,7 @@ class FSMultipartFormData : public EncodingFormSubmission { nsCOMPtr& aOutURI) override; void GetContentType(nsACString& aContentType) { - aContentType = - NS_LITERAL_CSTRING("multipart/form-data; boundary=") + mBoundary; + aContentType = "multipart/form-data; boundary="_ns + mBoundary; } nsIInputStream* GetSubmissionBody(uint64_t* aContentLength); diff --git a/dom/html/HTMLIFrameElement.cpp b/dom/html/HTMLIFrameElement.cpp index c7f6d3f10244..4e4d5a4d3f70 100644 --- a/dom/html/HTMLIFrameElement.cpp +++ b/dom/html/HTMLIFrameElement.cpp @@ -313,11 +313,11 @@ void HTMLIFrameElement::RefreshFeaturePolicy(bool aParseAllowAttribute) { } if (AllowPaymentRequest()) { - mFeaturePolicy->MaybeSetAllowedPolicy(NS_LITERAL_STRING("payment")); + mFeaturePolicy->MaybeSetAllowedPolicy(u"payment"_ns); } if (AllowFullscreen()) { - mFeaturePolicy->MaybeSetAllowedPolicy(NS_LITERAL_STRING("fullscreen")); + mFeaturePolicy->MaybeSetAllowedPolicy(u"fullscreen"_ns); } mFeaturePolicy->InheritPolicy(OwnerDoc()->FeaturePolicy()); diff --git a/dom/html/HTMLInputElement.cpp b/dom/html/HTMLInputElement.cpp index 4cfe2e7afb8f..5c3c5d2083b8 100644 --- a/dom/html/HTMLInputElement.cpp +++ b/dom/html/HTMLInputElement.cpp @@ -242,7 +242,7 @@ class DispatchChangeEventCallback final : public GetFilesCallback { rv = nsContentUtils::DispatchTrustedEvent( mInputElement->OwnerDoc(), static_cast(mInputElement.get()), - NS_LITERAL_STRING("change"), CanBubble::eYes, Cancelable::eNo); + u"change"_ns, CanBubble::eYes, Cancelable::eNo); return rv; } @@ -625,8 +625,8 @@ nsColorPickerShownCallback::Done(const nsAString& aColor) { if (mValueChanged) { rv = nsContentUtils::DispatchTrustedEvent( - mInput->OwnerDoc(), static_cast(mInput.get()), - NS_LITERAL_STRING("change"), CanBubble::eYes, Cancelable::eNo); + mInput->OwnerDoc(), static_cast(mInput.get()), u"change"_ns, + CanBubble::eYes, Cancelable::eNo); } return rv; @@ -808,7 +808,7 @@ nsresult HTMLInputElement::InitFilePicker(FilePickerType aType) { return NS_OK; } -#define CPS_PREF_NAME NS_LITERAL_STRING("browser.upload.lastDir") +#define CPS_PREF_NAME u"browser.upload.lastDir"_ns NS_IMPL_ISUPPORTS(UploadLastDir, nsIObserver, nsISupportsWeakReference) @@ -1302,9 +1302,8 @@ nsresult HTMLInputElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName, if (Element* dateTimeBoxElement = GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( dateTimeBoxElement, - aName == nsGkAtoms::value - ? NS_LITERAL_STRING("MozDateTimeValueChanged") - : NS_LITERAL_STRING("MozDateTimeAttributeChanged"), + aName == nsGkAtoms::value ? u"MozDateTimeValueChanged"_ns + : u"MozDateTimeAttributeChanged"_ns, CanBubble::eNo, ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); } @@ -2040,7 +2039,7 @@ void HTMLInputElement::MozSetFileNameArray(const Sequence& aFileNames, for (uint32_t i = 0; i < aFileNames.Length(); ++i) { nsCOMPtr file; - if (StringBeginsWith(aFileNames[i], NS_LITERAL_STRING("file:"), + if (StringBeginsWith(aFileNames[i], u"file:"_ns, nsASCIICaseInsensitiveStringComparator)) { // Converts the URL string into the corresponding nsIFile if possible // A local file will be created if the URL string begins with file:// @@ -2134,10 +2133,9 @@ void HTMLInputElement::OpenDateTimePicker(const DateTimeValue& aInitialValue) { } mDateTimeInputBoxValue = MakeUnique(aInitialValue); - nsContentUtils::DispatchChromeEvent( - OwnerDoc(), static_cast(this), - NS_LITERAL_STRING("MozOpenDateTimePicker"), CanBubble::eYes, - Cancelable::eYes); + nsContentUtils::DispatchChromeEvent(OwnerDoc(), static_cast(this), + u"MozOpenDateTimePicker"_ns, + CanBubble::eYes, Cancelable::eYes); } void HTMLInputElement::UpdateDateTimePicker(const DateTimeValue& aValue) { @@ -2146,10 +2144,9 @@ void HTMLInputElement::UpdateDateTimePicker(const DateTimeValue& aValue) { } mDateTimeInputBoxValue = MakeUnique(aValue); - nsContentUtils::DispatchChromeEvent( - OwnerDoc(), static_cast(this), - NS_LITERAL_STRING("MozUpdateDateTimePicker"), CanBubble::eYes, - Cancelable::eYes); + nsContentUtils::DispatchChromeEvent(OwnerDoc(), static_cast(this), + u"MozUpdateDateTimePicker"_ns, + CanBubble::eYes, Cancelable::eYes); } void HTMLInputElement::CloseDateTimePicker() { @@ -2157,10 +2154,9 @@ void HTMLInputElement::CloseDateTimePicker() { return; } - nsContentUtils::DispatchChromeEvent( - OwnerDoc(), static_cast(this), - NS_LITERAL_STRING("MozCloseDateTimePicker"), CanBubble::eYes, - Cancelable::eYes); + nsContentUtils::DispatchChromeEvent(OwnerDoc(), static_cast(this), + u"MozCloseDateTimePicker"_ns, + CanBubble::eYes, Cancelable::eYes); } void HTMLInputElement::SetFocusState(bool aIsFocused) { @@ -2537,8 +2533,8 @@ void HTMLInputElement::FireChangeEventIfNeeded() { // Dispatch the change event. mFocusedValue = value; nsContentUtils::DispatchTrustedEvent( - OwnerDoc(), static_cast(this), NS_LITERAL_STRING("change"), - CanBubble::eYes, Cancelable::eNo); + OwnerDoc(), static_cast(this), u"change"_ns, CanBubble::eYes, + Cancelable::eNo); } FileList* HTMLInputElement::GetFiles() { @@ -2683,9 +2679,8 @@ nsresult HTMLInputElement::SetValueInternal(const nsAString& aValue, !(aFlags & TextControlState::eSetValue_BySetUserInput)) { if (Element* dateTimeBoxElement = GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - dateTimeBoxElement, - NS_LITERAL_STRING("MozDateTimeValueChanged"), CanBubble::eNo, - ChromeOnlyDispatch::eNo); + dateTimeBoxElement, u"MozDateTimeValueChanged"_ns, + CanBubble::eNo, ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); } } @@ -2954,8 +2949,8 @@ void HTMLInputElement::Blur(ErrorResult& aError) { !IsExperimentalMobileType(mType)) { if (Element* dateTimeBoxElement = GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - dateTimeBoxElement, NS_LITERAL_STRING("MozBlurInnerTextBox"), - CanBubble::eNo, ChromeOnlyDispatch::eNo); + dateTimeBoxElement, u"MozBlurInnerTextBox"_ns, CanBubble::eNo, + ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); return; } @@ -2970,8 +2965,8 @@ void HTMLInputElement::Focus(const FocusOptions& aOptions, !IsExperimentalMobileType(mType)) { if (Element* dateTimeBoxElement = GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - dateTimeBoxElement, NS_LITERAL_STRING("MozFocusInnerTextBox"), - CanBubble::eNo, ChromeOnlyDispatch::eNo); + dateTimeBoxElement, u"MozFocusInnerTextBox"_ns, CanBubble::eNo, + ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); return; } @@ -3234,8 +3229,8 @@ void HTMLInputElement::GetEventTargetParent(EventChainPreVisitor& aVisitor) { // pass the focus to the inner text control. if (Element* dateTimeBoxElement = GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - dateTimeBoxElement, NS_LITERAL_STRING("MozFocusInnerTextBox"), - CanBubble::eNo, ChromeOnlyDispatch::eNo); + dateTimeBoxElement, u"MozFocusInnerTextBox"_ns, CanBubble::eNo, + ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); } } @@ -3423,8 +3418,7 @@ void HTMLInputElement::StartNumberControlSpinnerSpin() { mNumberControlSpinnerIsSpinning = true; nsRepeatService::GetInstance()->Start( - HandleNumberControlSpin, this, OwnerDoc(), - NS_LITERAL_CSTRING("HandleNumberControlSpin")); + HandleNumberControlSpin, this, OwnerDoc(), "HandleNumberControlSpin"_ns); // Capture the mouse so that we can tell if the pointer moves from one // spin button to the other, or to some other element: @@ -4232,9 +4226,9 @@ nsresult HTMLInputElement::BindToTree(BindContext& aContext, nsINode& aParent) { if (mType == NS_FORM_INPUT_PASSWORD) { if (IsInComposedDoc()) { - AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("DOMInputPasswordAdded"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + AsyncEventDispatcher* dispatcher = + new AsyncEventDispatcher(this, u"DOMInputPasswordAdded"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->PostDOMEvent(); } @@ -4474,9 +4468,9 @@ void HTMLInputElement::HandleTypeChange(uint8_t aNewType, bool aNotify) { } if (mType == NS_FORM_INPUT_PASSWORD && IsInComposedDoc()) { - AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("DOMInputPasswordAdded"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + AsyncEventDispatcher* dispatcher = + new AsyncEventDispatcher(this, u"DOMInputPasswordAdded"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->PostDOMEvent(); } @@ -5270,7 +5264,7 @@ already_AddRefed HTMLInputElement::GetFilesAndDirectories( // In future we could refactor SetFilePickerFiltersFromAccept to return a // semicolon separated list of file extensions and include that in the // filter string passed here. - directory->SetContentFilters(NS_LITERAL_STRING("filter-out-sensitive")); + directory->SetContentFilters(u"filter-out-sensitive"_ns); filesAndDirsSeq[i].SetAsDirectory() = directory; } else { MOZ_ASSERT(filesAndDirs[i].IsFile()); @@ -5625,13 +5619,13 @@ HTMLInputElement::SubmitNamesValues(HTMLFormSubmission* aFormSubmission) { yVal.AppendInt(y); if (!name.IsEmpty()) { - aFormSubmission->AddNameValuePair(name + NS_LITERAL_STRING(".x"), xVal); - aFormSubmission->AddNameValuePair(name + NS_LITERAL_STRING(".y"), yVal); + aFormSubmission->AddNameValuePair(name + u".x"_ns, xVal); + aFormSubmission->AddNameValuePair(name + u".y"_ns, yVal); } else { // If the Image Element has no name, simply return x and y // to Nav and IE compatibility. - aFormSubmission->AddNameValuePair(NS_LITERAL_STRING("x"), xVal); - aFormSubmission->AddNameValuePair(NS_LITERAL_STRING("y"), yVal); + aFormSubmission->AddNameValuePair(u"x"_ns, xVal); + aFormSubmission->AddNameValuePair(u"y"_ns, yVal); } return NS_OK; @@ -6729,7 +6723,7 @@ void HTMLInputElement::SetFilePickerFiltersFromAccept( // Ignore this filter as it contains reserved characters continue; } - extensionListStr = NS_LITERAL_STRING("*") + token; + extensionListStr = u"*"_ns + token; filterName = extensionListStr; atLeastOneFileExtensionFilter = true; } else { @@ -6766,8 +6760,7 @@ void HTMLInputElement::SetFilePickerFiltersFromAccept( if (!extensionListStr.IsEmpty()) { extensionListStr.AppendLiteral("; "); } - extensionListStr += - NS_LITERAL_STRING("*.") + NS_ConvertUTF8toUTF16(extension); + extensionListStr += u"*."_ns + NS_ConvertUTF8toUTF16(extension); } } @@ -6817,8 +6810,8 @@ void HTMLInputElement::SetFilePickerFiltersFromAccept( // Add an extra "; " to be sure the check will work and avoid cases like // "*.xls" being a subtring of "*.xslx" while those are two differents // filters and none should be removed. - if (FindInReadable(filterToCheck.mFilter + NS_LITERAL_STRING(";"), - filtersCopy[j].mFilter + NS_LITERAL_STRING(";"))) { + if (FindInReadable(filterToCheck.mFilter + u";"_ns, + filtersCopy[j].mFilter + u";"_ns)) { // We already have a similar, less restrictive filter (i.e. // filterToCheck extensionList is just a subset of another filter // extension list): remove this one diff --git a/dom/html/HTMLLinkElement.cpp b/dom/html/HTMLLinkElement.cpp index cd4c63bbbcc9..baca784fc61f 100644 --- a/dom/html/HTMLLinkElement.cpp +++ b/dom/html/HTMLLinkElement.cpp @@ -137,11 +137,11 @@ nsresult HTMLLinkElement::BindToTree(BindContext& aContext, nsINode& aParent) { } void HTMLLinkElement::LinkAdded() { - CreateAndDispatchEvent(OwnerDoc(), NS_LITERAL_STRING("DOMLinkAdded")); + CreateAndDispatchEvent(OwnerDoc(), u"DOMLinkAdded"_ns); } void HTMLLinkElement::LinkRemoved() { - CreateAndDispatchEvent(OwnerDoc(), NS_LITERAL_STRING("DOMLinkRemoved")); + CreateAndDispatchEvent(OwnerDoc(), u"DOMLinkRemoved"_ns); } void HTMLLinkElement::UnbindFromTree(bool aNullParent) { @@ -170,7 +170,7 @@ void HTMLLinkElement::UnbindFromTree(bool aNullParent) { oldDoc->LocalizationLinkRemoved(this); } - CreateAndDispatchEvent(oldDoc, NS_LITERAL_STRING("DOMLinkRemoved")); + CreateAndDispatchEvent(oldDoc, u"DOMLinkRemoved"_ns); nsGenericHTMLElement::UnbindFromTree(aNullParent); Unused << UpdateStyleSheetInternal(oldDoc, oldShadowRoot); @@ -260,7 +260,7 @@ nsresult HTMLLinkElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName, bool hasHref = aValue; Link::ResetLinkState(!!aNotify, hasHref); if (IsInUncomposedDoc()) { - CreateAndDispatchEvent(OwnerDoc(), NS_LITERAL_STRING("DOMLinkChanged")); + CreateAndDispatchEvent(OwnerDoc(), u"DOMLinkChanged"_ns); } } @@ -833,8 +833,8 @@ bool HTMLLinkElement::CheckPreloadAttrs(const nsAttrValue& aAs, } if (policyType == nsIContentPolicy::TYPE_IMAGE) { return imgLoader::SupportImageWithMimeType( - NS_ConvertUTF16toUTF8(type).get(), - AcceptedMimeTypes::IMAGES_AND_DOCUMENTS); + NS_ConvertUTF16toUTF8(type).get(), + AcceptedMimeTypes::IMAGES_AND_DOCUMENTS); } if (policyType == nsIContentPolicy::TYPE_SCRIPT) { return nsContentUtils::IsJavascriptMIMEType(type); diff --git a/dom/html/HTMLMarqueeElement.cpp b/dom/html/HTMLMarqueeElement.cpp index 61ef7c207560..7fe30b4279f3 100644 --- a/dom/html/HTMLMarqueeElement.cpp +++ b/dom/html/HTMLMarqueeElement.cpp @@ -163,13 +163,13 @@ void HTMLMarqueeElement::DispatchEventToShadowRoot( void HTMLMarqueeElement::Start() { if (GetShadowRoot()) { - DispatchEventToShadowRoot(NS_LITERAL_STRING("marquee-start")); + DispatchEventToShadowRoot(u"marquee-start"_ns); } } void HTMLMarqueeElement::Stop() { if (GetShadowRoot()) { - DispatchEventToShadowRoot(NS_LITERAL_STRING("marquee-stop")); + DispatchEventToShadowRoot(u"marquee-stop"_ns); } } diff --git a/dom/html/HTMLMediaElement.cpp b/dom/html/HTMLMediaElement.cpp index f199375fe64d..483a68668fc7 100644 --- a/dom/html/HTMLMediaElement.cpp +++ b/dom/html/HTMLMediaElement.cpp @@ -355,7 +355,7 @@ class HTMLMediaElement::nsNotifyAboutPlayingRunner return NS_OK; } - mElement->DispatchEvent(NS_LITERAL_STRING("playing")); + mElement->DispatchEvent(u"playing"_ns); return nsResolveOrRejectPendingPlayPromisesRunner::Run(); } }; @@ -374,9 +374,9 @@ class nsSourceErrorEventRunner : public nsMediaEvent { if (IsCancelled()) return NS_OK; LOG_EVENT(LogLevel::Debug, ("%p Dispatching simple event source error", mElement.get())); - return nsContentUtils::DispatchTrustedEvent( - mElement->OwnerDoc(), mSource, NS_LITERAL_STRING("error"), - CanBubble::eNo, Cancelable::eNo); + return nsContentUtils::DispatchTrustedEvent(mElement->OwnerDoc(), mSource, + u"error"_ns, CanBubble::eNo, + Cancelable::eNo); } }; @@ -1322,7 +1322,7 @@ HTMLMediaElement::MediaLoadListener::OnStartRequest(nsIRequest* aRequest) { if (NS_FAILED(rv) && !mNextListener) { // Load failed, attempt to load the next candidate resource. If there // are none, this will trigger a MEDIA_ERR_SRC_NOT_SUPPORTED error. - element->NotifyLoadError(NS_LITERAL_CSTRING("Failed to init decoder")); + element->NotifyLoadError("Failed to init decoder"_ns); } // If InitializeDecoderForChannel did not return a listener (but may // have otherwise succeeded), we abort the connection since we aren't @@ -1397,9 +1397,9 @@ void HTMLMediaElement::ReportLoadError(const char* aMsg, void HTMLMediaElement::ReportToConsole( uint32_t aErrorFlags, const char* aMsg, const nsTArray& aParams) const { - nsContentUtils::ReportToConsole(aErrorFlags, NS_LITERAL_CSTRING("Media"), - OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, - aMsg, aParams); + nsContentUtils::ReportToConsole(aErrorFlags, "Media"_ns, OwnerDoc(), + nsContentUtils::eDOM_PROPERTIES, aMsg, + aParams); } class HTMLMediaElement::AudioChannelAgentCallback final @@ -1704,7 +1704,7 @@ class HTMLMediaElement::ChannelLoader final { if (NS_FAILED(rv)) { // Notify load error so the element will try next resource candidate. - aElement->NotifyLoadError(NS_LITERAL_CSTRING("Fail to create channel")); + aElement->NotifyLoadError("Fail to create channel"_ns); return; } @@ -1745,8 +1745,7 @@ class HTMLMediaElement::ChannelLoader final { // Use a byte range request from the start of the resource. // This enables us to detect if the stream supports byte range // requests, and therefore seeking, early. - rv = hc->SetRequestHeader(NS_LITERAL_CSTRING("Range"), - NS_LITERAL_CSTRING("bytes=0-"), false); + rv = hc->SetRequestHeader("Range"_ns, "bytes=0-"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); aElement->SetRequestHeaders(hc); } @@ -1754,7 +1753,7 @@ class HTMLMediaElement::ChannelLoader final { rv = channel->AsyncOpen(loadListener); if (NS_FAILED(rv)) { // Notify load error so the element will try next resource candidate. - aElement->NotifyLoadError(NS_LITERAL_CSTRING("Failed to open channel")); + aElement->NotifyLoadError("Failed to open channel"_ns); return; } @@ -1850,14 +1849,14 @@ class HTMLMediaElement::ErrorSink { } mError = new MediaError(mOwner, aErrorCode, aErrorDetails); - mOwner->DispatchAsyncEvent(NS_LITERAL_STRING("error")); + mOwner->DispatchAsyncEvent(u"error"_ns); if (mOwner->ReadyState() == HAVE_NOTHING && aErrorCode == MEDIA_ERR_ABORTED) { // https://html.spec.whatwg.org/multipage/embedded-content.html#media-data-processing-steps-list // "If the media data fetching process is aborted by the user" - mOwner->DispatchAsyncEvent(NS_LITERAL_STRING("abort")); + mOwner->DispatchAsyncEvent(u"abort"_ns); mOwner->ChangeNetworkState(NETWORK_EMPTY); - mOwner->DispatchAsyncEvent(NS_LITERAL_STRING("emptied")); + mOwner->DispatchAsyncEvent(u"emptied"_ns); if (mOwner->mDecoder) { mOwner->ShutdownDecoder(); } @@ -2225,7 +2224,7 @@ void HTMLMediaElement::AbortExistingLoads() { mMediaSource = nullptr; if (mNetworkState == NETWORK_LOADING || mNetworkState == NETWORK_IDLE) { - DispatchAsyncEvent(NS_LITERAL_STRING("abort")); + DispatchAsyncEvent(u"abort"_ns); } bool hadVideo = HasVideo(); @@ -2275,7 +2274,7 @@ void HTMLMediaElement::AbortExistingLoads() { // change will be reflected in the controls. FireTimeUpdate(false); } - DispatchAsyncEvent(NS_LITERAL_STRING("emptied")); + DispatchAsyncEvent(u"emptied"_ns); UpdateAudioChannelPlayingState(); } @@ -2391,15 +2390,15 @@ static bool HasSourceChildren(nsIContent* aElement) { static nsCString DocumentOrigin(Document* aDoc) { if (!aDoc) { - return NS_LITERAL_CSTRING("null"); + return "null"_ns; } nsCOMPtr principal = aDoc->NodePrincipal(); if (!principal) { - return NS_LITERAL_CSTRING("null"); + return "null"_ns; } nsCString origin; if (NS_FAILED(principal->GetOrigin(origin))) { - return NS_LITERAL_CSTRING("null"); + return "null"_ns; } return origin; } @@ -2496,7 +2495,7 @@ void HTMLMediaElement::SelectResource() { ChangeDelayLoadStatus(true); ChangeNetworkState(NETWORK_LOADING); - DispatchAsyncEvent(NS_LITERAL_STRING("loadstart")); + DispatchAsyncEvent(u"loadstart"_ns); // Delay setting mIsRunningSeletResource until after UpdatePreloadAction // so that we don't lose our state change by bailing out of the preload @@ -3011,7 +3010,7 @@ nsresult HTMLMediaElement::LoadWithChannel(nsIChannel* aChannel, } SetPlaybackRate(mDefaultPlaybackRate, IgnoreErrors()); - DispatchAsyncEvent(NS_LITERAL_STRING("loadstart")); + DispatchAsyncEvent(u"loadstart"_ns); return NS_OK; } @@ -3296,7 +3295,7 @@ void HTMLMediaElement::PauseInternal() { if (!oldPaused) { FireTimeUpdate(false); - DispatchAsyncEvent(NS_LITERAL_STRING("pause")); + DispatchAsyncEvent(u"pause"_ns); AsyncRejectPendingPlayPromises(NS_ERROR_DOM_MEDIA_ABORT_ERR); } } @@ -3316,7 +3315,7 @@ void HTMLMediaElement::SetVolume(double aVolume, ErrorResult& aRv) { // Here we want just to update the volume. SetVolumeInternal(); - DispatchAsyncEvent(NS_LITERAL_STRING("volumechange")); + DispatchAsyncEvent(u"volumechange"_ns); // We allow inaudible autoplay. But changing our volume may make this // media audible. So pause if we are no longer supposed to be autoplaying. @@ -3402,7 +3401,7 @@ void HTMLMediaElement::SetMuted(bool aMuted) { SetMutedInternal(mMuted & ~MUTED_BY_CONTENT); } - DispatchAsyncEvent(NS_LITERAL_STRING("volumechange")); + DispatchAsyncEvent(u"volumechange"_ns); // We allow inaudible autoplay. But changing our mute status may make this // media audible. So pause if we are no longer supposed to be autoplaying. @@ -4323,12 +4322,12 @@ already_AddRefed HTMLMediaElement::Play(ErrorResult& aRv) { void HTMLMediaElement::DispatchEventsWhenPlayWasNotAllowed() { if (StaticPrefs::media_autoplay_block_event_enabled()) { - DispatchAsyncEvent(NS_LITERAL_STRING("blocked")); + DispatchAsyncEvent(u"blocked"_ns); } #if defined(MOZ_WIDGET_ANDROID) - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("MozAutoplayMediaBlocked"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"MozAutoplayMediaBlocked"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->PostDOMEvent(); #endif MaybeNotifyAutoplayBlocked(); @@ -4345,9 +4344,9 @@ void HTMLMediaElement::MaybeNotifyAutoplayBlocked() { // This event is used to notify front-end side that we've blocked autoplay, // so front-end side should show blocking icon as well. - RefPtr asyncDispatcher = new AsyncEventDispatcher( - topLevelDoc, NS_LITERAL_STRING("GloballyAutoplayBlocked"), - CanBubble::eYes, ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(topLevelDoc, u"GloballyAutoplayBlocked"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->PostDOMEvent(); } @@ -4427,7 +4426,7 @@ void HTMLMediaElement::PlayInternal(bool aHandlingUserInput) { } // 6.3. Queue a task to fire a simple event named play at the element. - DispatchAsyncEvent(NS_LITERAL_STRING("play")); + DispatchAsyncEvent(u"play"_ns); // 6.4. If the media element's readyState attribute has the value // HAVE_NOTHING, HAVE_METADATA, or HAVE_CURRENT_DATA, queue a task to @@ -4437,11 +4436,11 @@ void HTMLMediaElement::PlayInternal(bool aHandlingUserInput) { // element. switch (mReadyState) { case HAVE_NOTHING: - DispatchAsyncEvent(NS_LITERAL_STRING("waiting")); + DispatchAsyncEvent(u"waiting"_ns); break; case HAVE_METADATA: case HAVE_CURRENT_DATA: - DispatchAsyncEvent(NS_LITERAL_STRING("waiting")); + DispatchAsyncEvent(u"waiting"_ns); break; case HAVE_FUTURE_DATA: case HAVE_ENOUGH_DATA: @@ -4488,7 +4487,7 @@ void HTMLMediaElement::CreateAudioWakeLockIfNeeded() { NS_ENSURE_TRUE_VOID(pmService); ErrorResult rv; - mWakeLock = pmService->NewWakeLock(NS_LITERAL_STRING("audio-playing"), + mWakeLock = pmService->NewWakeLock(u"audio-playing"_ns, OwnerDoc()->GetInnerWindow(), rv); } } @@ -4799,7 +4798,7 @@ void HTMLMediaElement::ReportTelemetry() { hiddenPercentage); // Also accumulate all percentages in an "All" key. Telemetry::Accumulate(Telemetry::VIDEO_HIDDEN_PLAY_TIME_PERCENTAGE, - NS_LITERAL_CSTRING("All"), hiddenPercentage); + "All"_ns, hiddenPercentage); LOG(LogLevel::Debug, ("%p VIDEO_HIDDEN_PLAY_TIME_PERCENTAGE = %u, keys: '%s' and 'All'", this, hiddenPercentage, key.get())); @@ -4809,8 +4808,7 @@ void HTMLMediaElement::ReportTelemetry() { Telemetry::Accumulate(Telemetry::VIDEO_INFERRED_DECODE_SUSPEND_PERCENTAGE, key, videoDecodeSuspendPercentage); Telemetry::Accumulate(Telemetry::VIDEO_INFERRED_DECODE_SUSPEND_PERCENTAGE, - NS_LITERAL_CSTRING("All"), - videoDecodeSuspendPercentage); + "All"_ns, videoDecodeSuspendPercentage); LOG(LogLevel::Debug, ("%p VIDEO_INFERRED_DECODE_SUSPEND_PERCENTAGE = %u, keys: '%s' and " "'All'", @@ -4825,7 +4823,7 @@ void HTMLMediaElement::ReportTelemetry() { Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_AVERAGE_MS, key, average_ms); Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_AVERAGE_MS, - NS_LITERAL_CSTRING("All"), average_ms); + "All"_ns, average_ms); LOG(LogLevel::Debug, ("%p VIDEO_INTER_KEYFRAME_AVERAGE_MS = %u, keys: '%s' and 'All'", this, average_ms, key.get())); @@ -4834,8 +4832,8 @@ void HTMLMediaElement::ReportTelemetry() { (data.mInterKeyFrameMax_us + 500) / 1000, UINT32_MAX)); Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_MAX_MS, key, max_ms); - Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_MAX_MS, - NS_LITERAL_CSTRING("All"), max_ms); + Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_MAX_MS, "All"_ns, + max_ms); LOG(LogLevel::Debug, ("%p VIDEO_INTER_KEYFRAME_MAX_MS = %u, keys: '%s' and 'All'", this, max_ms, key.get())); @@ -4848,7 +4846,7 @@ void HTMLMediaElement::ReportTelemetry() { if (uint32_t(playTime * 1000.0) > suspendDelay_ms) { Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_MAX_MS, key, 0); Telemetry::Accumulate(Telemetry::VIDEO_INTER_KEYFRAME_MAX_MS, - NS_LITERAL_CSTRING("All"), 0); + "All"_ns, 0); LOG(LogLevel::Debug, ("%p VIDEO_INTER_KEYFRAME_MAX_MS = 0 (only 1 keyframe), keys: " "'%s' and 'All'", @@ -5311,8 +5309,7 @@ static already_AddRefed CreateAudioTrack( aStreamTrack->GetId(id); aStreamTrack->GetLabel(label, CallerType::System); - return MediaTrackList::CreateAudioTrack(aOwnerGlobal, id, - NS_LITERAL_STRING("main"), label, + return MediaTrackList::CreateAudioTrack(aOwnerGlobal, id, u"main"_ns, label, EmptyString(), true, aStreamTrack); } @@ -5323,8 +5320,7 @@ static already_AddRefed CreateVideoTrack( aStreamTrack->GetId(id); aStreamTrack->GetLabel(label, CallerType::System); - return MediaTrackList::CreateVideoTrack(aOwnerGlobal, id, - NS_LITERAL_STRING("main"), label, + return MediaTrackList::CreateVideoTrack(aOwnerGlobal, id, u"main"_ns, label, EmptyString(), aStreamTrack); } @@ -5433,14 +5429,14 @@ void HTMLMediaElement::MetadataLoaded(const MediaInfo* aInfo, // "loadedmetadata" event handlers. UpdateOutputTrackSources(); - DispatchAsyncEvent(NS_LITERAL_STRING("durationchange")); + DispatchAsyncEvent(u"durationchange"_ns); if (IsVideo() && HasVideo()) { - DispatchAsyncEvent(NS_LITERAL_STRING("resize")); + DispatchAsyncEvent(u"resize"_ns); } NS_ASSERTION(!HasVideo() || (mMediaInfo.mVideo.mDisplay.width > 0 && mMediaInfo.mVideo.mDisplay.height > 0), "Video resolution must be known on 'loadedmetadata'"); - DispatchAsyncEvent(NS_LITERAL_STRING("loadedmetadata")); + DispatchAsyncEvent(u"loadedmetadata"_ns); if (mDecoder && mDecoder->IsTransportSeekable() && mDecoder->IsMediaSeekable()) { @@ -5563,7 +5559,7 @@ void HTMLMediaElement::PlaybackEnded() { LOG(LogLevel::Debug, ("%p, got duration by reaching the end of the resource", this)); mSrcStreamPlaybackEnded = true; - DispatchAsyncEvent(NS_LITERAL_STRING("durationchange")); + DispatchAsyncEvent(u"durationchange"_ns); } else { // mediacapture-main: // Setting the loop attribute has no effect since a MediaStream has no @@ -5586,16 +5582,14 @@ void HTMLMediaElement::PlaybackEnded() { mAutoplaying = true; } - DispatchAsyncEvent(NS_LITERAL_STRING("ended")); + DispatchAsyncEvent(u"ended"_ns); } void HTMLMediaElement::UpdateSrcStreamReportPlaybackEnded() { mSrcStreamReportPlaybackEnded = mSrcStreamPlaybackEnded; } -void HTMLMediaElement::SeekStarted() { - DispatchAsyncEvent(NS_LITERAL_STRING("seeking")); -} +void HTMLMediaElement::SeekStarted() { DispatchAsyncEvent(u"seeking"_ns); } void HTMLMediaElement::SeekCompleted() { mPlayingBeforeSeek = false; @@ -5604,7 +5598,7 @@ void HTMLMediaElement::SeekCompleted() { mTextTrackManager->DidSeek(); } FireTimeUpdate(false); - DispatchAsyncEvent(NS_LITERAL_STRING("seeked")); + DispatchAsyncEvent(u"seeked"_ns); // We changed whether we're seeking so we need to AddRemoveSelfReference AddRemoveSelfReference(); if (mCurrentPlayRangeStart == -1.0) { @@ -5643,7 +5637,7 @@ void HTMLMediaElement::NotifySuspendedByCache(bool aSuspendedByCache) { void HTMLMediaElement::DownloadSuspended() { if (mNetworkState == NETWORK_LOADING) { - DispatchAsyncEvent(NS_LITERAL_STRING("progress")); + DispatchAsyncEvent(u"progress"_ns); } ChangeNetworkState(NETWORK_IDLE); } @@ -5673,7 +5667,7 @@ void HTMLMediaElement::CheckProgress(bool aHaveNewProgress) { : (now - mProgressTime >= TimeDuration::FromMilliseconds(PROGRESS_MS) && mDataTime > mProgressTime)) { - DispatchAsyncEvent(NS_LITERAL_STRING("progress")); + DispatchAsyncEvent(u"progress"_ns); // Resolution() ensures that future data will have now > mProgressTime, // and so will trigger another event. mDataTime is not reset because it // is still required to detect stalled; it is similarly offset by @@ -5698,7 +5692,7 @@ void HTMLMediaElement::CheckProgress(bool aHaveNewProgress) { if (now - mDataTime >= TimeDuration::FromMilliseconds(STALL_MS)) { if (!mMediaSource) { - DispatchAsyncEvent(NS_LITERAL_STRING("stalled")); + DispatchAsyncEvent(u"stalled"_ns); } else { ChangeDelayLoadStatus(false); } @@ -5855,7 +5849,7 @@ void HTMLMediaElement::UpdateReadyStateInternal() { // Note: Playback will already be stalled, as the next frame is // unavailable. mWaitingForKey = WAITING_FOR_KEY_DISPATCHED; - DispatchAsyncEvent(NS_LITERAL_STRING("waitingforkey")); + DispatchAsyncEvent(u"waitingforkey"_ns); } } else { MOZ_ASSERT(mWaitingForKey == WAITING_FOR_KEY_DISPATCHED); @@ -6005,21 +5999,21 @@ void HTMLMediaElement::ChangeReadyState(nsMediaReadyState aState) { // must queue a task to fire a simple event named timeupdate at the element, // and queue a task to fire a simple event named waiting at the element." if (mPlayingBeforeSeek && mReadyState < HAVE_FUTURE_DATA) { - DispatchAsyncEvent(NS_LITERAL_STRING("waiting")); + DispatchAsyncEvent(u"waiting"_ns); } else if (oldState >= HAVE_FUTURE_DATA && mReadyState < HAVE_FUTURE_DATA && !Paused() && !Ended() && !mErrorSink->mError) { FireTimeUpdate(false); - DispatchAsyncEvent(NS_LITERAL_STRING("waiting")); + DispatchAsyncEvent(u"waiting"_ns); } if (oldState < HAVE_CURRENT_DATA && mReadyState >= HAVE_CURRENT_DATA && !mLoadedDataFired) { - DispatchAsyncEvent(NS_LITERAL_STRING("loadeddata")); + DispatchAsyncEvent(u"loadeddata"_ns); mLoadedDataFired = true; } if (oldState < HAVE_FUTURE_DATA && mReadyState >= HAVE_FUTURE_DATA) { - DispatchAsyncEvent(NS_LITERAL_STRING("canplay")); + DispatchAsyncEvent(u"canplay"_ns); if (!mPaused) { if (mDecoder && !mSuspendedByInactiveDocOrDocshell) { MOZ_ASSERT(AutoplayPolicy::IsAllowedToPlay(*this)); @@ -6032,7 +6026,7 @@ void HTMLMediaElement::ChangeReadyState(nsMediaReadyState aState) { CheckAutoplayDataReady(); if (oldState < HAVE_ENOUGH_DATA && mReadyState >= HAVE_ENOUGH_DATA) { - DispatchAsyncEvent(NS_LITERAL_STRING("canplaythrough")); + DispatchAsyncEvent(u"canplaythrough"_ns); } } @@ -6061,7 +6055,7 @@ void HTMLMediaElement::ChangeNetworkState(nsMediaNetworkState aState) { StartProgress(); } else if (mNetworkState == NETWORK_IDLE && !mErrorSink->mError) { // Fire 'suspend' event when entering NETWORK_IDLE and no error presented. - DispatchAsyncEvent(NS_LITERAL_STRING("suspend")); + DispatchAsyncEvent(u"suspend"_ns); } // According to the resource selection (step2, step9-18), dedicated media @@ -6158,9 +6152,9 @@ void HTMLMediaElement::CheckAutoplayDataReady() { } // For blocked media, the event would be pending until it is resumed. - DispatchAsyncEvent(NS_LITERAL_STRING("play")); + DispatchAsyncEvent(u"play"_ns); - DispatchAsyncEvent(NS_LITERAL_STRING("playing")); + DispatchAsyncEvent(u"playing"_ns); } bool HTMLMediaElement::IsActive() const { @@ -6423,7 +6417,7 @@ void HTMLMediaElement::UpdateMediaSize(const nsIntSize& aSize) { if (IsVideo() && mReadyState != HAVE_NOTHING && mMediaInfo.mVideo.mDisplay != aSize) { - DispatchAsyncEvent(NS_LITERAL_STRING("resize")); + DispatchAsyncEvent(u"resize"_ns); } mMediaInfo.mVideo.mDisplay = aSize; @@ -6503,7 +6497,7 @@ void HTMLMediaElement::SuspendOrResumeElement(bool aSuspendElement) { } if (StaticPrefs::media_testing_only_events()) { auto dispatcher = MakeRefPtr( - this, NS_LITERAL_STRING("MozMediaSuspendChanged"), CanBubble::eYes, + this, u"MozMediaSuspendChanged"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes); dispatcher->PostDOMEvent(); } @@ -6716,8 +6710,8 @@ void HTMLMediaElement::SetRequestHeaders(nsIHttpChannel* aChannel) { // Content-Duration and a length spec in the container are not present either) // and from seeking. So, disable the standard "Accept-Encoding: gzip,deflate" // that we usually send. See bug 614760. - DebugOnly rv = aChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Accept-Encoding"), EmptyCString(), false); + DebugOnly rv = + aChannel->SetRequestHeader("Accept-Encoding"_ns, EmptyCString(), false); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Set the Referrer header @@ -6743,7 +6737,7 @@ void HTMLMediaElement::FireTimeUpdate(bool aPeriodic) { (mTimeUpdateTime.IsNull() || now - mTimeUpdateTime >= TimeDuration::FromMilliseconds(TIMEUPDATE_MS)))) { - DispatchAsyncEvent(NS_LITERAL_STRING("timeupdate")); + DispatchAsyncEvent(u"timeupdate"_ns); mTimeUpdateTime = now; mLastCurrentTime = time; } @@ -6800,7 +6794,7 @@ void HTMLMediaElement::SetDefaultPlaybackRate(double aDefaultPlaybackRate, } mDefaultPlaybackRate = defaultPlaybackRate; - DispatchAsyncEvent(NS_LITERAL_STRING("ratechange")); + DispatchAsyncEvent(u"ratechange"_ns); } void HTMLMediaElement::SetPlaybackRate(double aPlaybackRate, ErrorResult& aRv) { @@ -6832,7 +6826,7 @@ void HTMLMediaElement::SetPlaybackRate(double aPlaybackRate, ErrorResult& aRv) { if (mDecoder) { mDecoder->SetPlaybackRate(ClampPlaybackRate(mPlaybackRate)); } - DispatchAsyncEvent(NS_LITERAL_STRING("ratechange")); + DispatchAsyncEvent(u"ratechange"_ns); } void HTMLMediaElement::SetMozPreservesPitch(bool aPreservesPitch) { @@ -6875,7 +6869,7 @@ void HTMLMediaElement::OnVisibilityChange(Visibility aNewVisibility) { mVisibilityState = aNewVisibility; if (StaticPrefs::media_test_video_suspend()) { - DispatchAsyncEvent(NS_LITERAL_STRING("visibilitychanged")); + DispatchAsyncEvent(u"visibilitychanged"_ns); } if (!mDecoder) { @@ -7088,8 +7082,7 @@ already_AddRefed HTMLMediaElement::SetMediaKeys( return nullptr; } RefPtr promise = DetailedPromise::Create( - win->AsGlobal(), aRv, - NS_LITERAL_CSTRING("HTMLMediaElement.setMediaKeys")); + win->AsGlobal(), aRv, "HTMLMediaElement.setMediaKeys"_ns); if (aRv.Failed()) { return nullptr; } @@ -7449,7 +7442,7 @@ nsTArray> HTMLMediaElement::TakePendingPlayPromises() { void HTMLMediaElement::NotifyAboutPlaying() { // Stick to the DispatchAsyncEvent() call path for now because we want to // trigger some telemetry-related codes in the DispatchAsyncEvent() method. - DispatchAsyncEvent(NS_LITERAL_STRING("playing")); + DispatchAsyncEvent(u"playing"_ns); } already_AddRefed HTMLMediaElement::CreatePlayPromise( @@ -7493,7 +7486,7 @@ void HTMLMediaElement::AsyncResolvePendingPlayPromises() { void HTMLMediaElement::AsyncRejectPendingPlayPromises(nsresult aError) { if (!mPaused) { mPaused = true; - DispatchAsyncEvent(NS_LITERAL_STRING("pause")); + DispatchAsyncEvent(u"pause"_ns); } if (mShuttingDown) { diff --git a/dom/html/HTMLMetaElement.cpp b/dom/html/HTMLMetaElement.cpp index 4255da3a2e4f..a9302605f8a4 100644 --- a/dom/html/HTMLMetaElement.cpp +++ b/dom/html/HTMLMetaElement.cpp @@ -61,7 +61,7 @@ nsresult HTMLMetaElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName, nsGkAtoms::viewport, eIgnoreCase)) { ProcessViewportContent(document); } - CreateAndDispatchEvent(document, NS_LITERAL_STRING("DOMMetaChanged")); + CreateAndDispatchEvent(document, u"DOMMetaChanged"_ns); } else if (document && aName == nsGkAtoms::name) { if (aValue && aValue->Equals(nsGkAtoms::viewport, eIgnoreCase)) { ProcessViewportContent(document); @@ -69,7 +69,7 @@ nsresult HTMLMetaElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName, aOldValue->Equals(nsGkAtoms::viewport, eIgnoreCase)) { DiscardViewportContent(document); } - CreateAndDispatchEvent(document, NS_LITERAL_STRING("DOMMetaChanged")); + CreateAndDispatchEvent(document, u"DOMMetaChanged"_ns); } // Update referrer policy when it got changed from JS SetMetaReferrer(document); @@ -119,7 +119,7 @@ nsresult HTMLMetaElement::BindToTree(BindContext& aContext, nsINode& aParent) { // Referrer Policy spec requires a element. SetMetaReferrer(&doc); - CreateAndDispatchEvent(&doc, NS_LITERAL_STRING("DOMMetaAdded")); + CreateAndDispatchEvent(&doc, u"DOMMetaAdded"_ns); return rv; } @@ -129,7 +129,7 @@ void HTMLMetaElement::UnbindFromTree(bool aNullParent) { nsGkAtoms::viewport, eIgnoreCase)) { DiscardViewportContent(oldDoc); } - CreateAndDispatchEvent(oldDoc, NS_LITERAL_STRING("DOMMetaRemoved")); + CreateAndDispatchEvent(oldDoc, u"DOMMetaRemoved"_ns); nsGenericHTMLElement::UnbindFromTree(aNullParent); } diff --git a/dom/html/HTMLScriptElement.cpp b/dom/html/HTMLScriptElement.cpp index 4cf9e47781d7..581221c616cb 100644 --- a/dom/html/HTMLScriptElement.cpp +++ b/dom/html/HTMLScriptElement.cpp @@ -187,19 +187,19 @@ void HTMLScriptElement::FreezeExecutionAttrs(Document* aOwnerDoc) { OwnerDoc(), GetBaseURI()); if (!mUri) { - AutoTArray params = {NS_LITERAL_STRING("src"), src}; + AutoTArray params = {u"src"_ns, src}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("HTML"), OwnerDoc(), + nsIScriptError::warningFlag, "HTML"_ns, OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, "ScriptSourceInvalidUri", params, nullptr, EmptyString(), GetScriptLineNumber(), GetScriptColumnNumber()); } } else { - AutoTArray params = {NS_LITERAL_STRING("src")}; + AutoTArray params = {u"src"_ns}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("HTML"), OwnerDoc(), + nsIScriptError::warningFlag, "HTML"_ns, OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, nullptr, EmptyString(), GetScriptLineNumber(), GetScriptColumnNumber()); } diff --git a/dom/html/HTMLSharedElement.cpp b/dom/html/HTMLSharedElement.cpp index c4e5de023fcc..4d82dbb84ab9 100644 --- a/dom/html/HTMLSharedElement.cpp +++ b/dom/html/HTMLSharedElement.cpp @@ -61,9 +61,9 @@ void HTMLSharedElement::DoneAddingChildren(bool aHaveNotified) { doc->OnL10nResourceContainerParsed(); } - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("DOMHeadElementParsed"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"DOMHeadElementParsed"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); // Always run async in order to avoid running script when the content // sink isn't expecting it. asyncDispatcher->PostDOMEvent(); diff --git a/dom/html/HTMLSlotElement.cpp b/dom/html/HTMLSlotElement.cpp index 725be314fbae..c9178c8ba000 100644 --- a/dom/html/HTMLSlotElement.cpp +++ b/dom/html/HTMLSlotElement.cpp @@ -209,8 +209,8 @@ void HTMLSlotElement::EnqueueSlotChangeEvent() { void HTMLSlotElement::FireSlotChangeEvent() { nsContentUtils::DispatchTrustedEvent( - OwnerDoc(), static_cast(this), - NS_LITERAL_STRING("slotchange"), CanBubble::eYes, Cancelable::eNo); + OwnerDoc(), static_cast(this), u"slotchange"_ns, + CanBubble::eYes, Cancelable::eNo); } JSObject* HTMLSlotElement::WrapNode(JSContext* aCx, diff --git a/dom/html/HTMLTextAreaElement.cpp b/dom/html/HTMLTextAreaElement.cpp index 40fe6e97e489..9932e8c1a9c4 100644 --- a/dom/html/HTMLTextAreaElement.cpp +++ b/dom/html/HTMLTextAreaElement.cpp @@ -510,8 +510,8 @@ void HTMLTextAreaElement::FireChangeEventIfNeeded() { // Dispatch the change event. mFocusedValue = value; nsContentUtils::DispatchTrustedEvent( - OwnerDoc(), static_cast(this), NS_LITERAL_STRING("change"), - CanBubble::eYes, Cancelable::eNo); + OwnerDoc(), static_cast(this), u"change"_ns, CanBubble::eYes, + Cancelable::eNo); } nsresult HTMLTextAreaElement::PostHandleEvent(EventChainPostVisitor& aVisitor) { diff --git a/dom/html/HTMLTrackElement.cpp b/dom/html/HTMLTrackElement.cpp index a5f2c0a1a639..34d7f31c6ea8 100644 --- a/dom/html/HTMLTrackElement.cpp +++ b/dom/html/HTMLTrackElement.cpp @@ -170,7 +170,7 @@ void HTMLTrackElement::CreateTextTrack() { nsCOMPtr window = do_QueryInterface(parentObject); if (!parentObject) { nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Media"), OwnerDoc(), + nsIScriptError::errorFlag, "Media"_ns, OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, "Using track element in non-window context"); return; @@ -439,11 +439,11 @@ void HTMLTrackElement::SetReadyState(TextTrackReadyState aReadyState) { switch (aReadyState) { case TextTrackReadyState::Loaded: LOG("dispatch 'load' event"); - DispatchTrackRunnable(NS_LITERAL_STRING("load")); + DispatchTrackRunnable(u"load"_ns); break; case TextTrackReadyState::FailedToLoad: LOG("dispatch 'error' event"); - DispatchTrackRunnable(NS_LITERAL_STRING("error")); + DispatchTrackRunnable(u"error"_ns); break; default: break; diff --git a/dom/html/HTMLVideoElement.cpp b/dom/html/HTMLVideoElement.cpp index 64383d3dc6db..6bf0abb43e98 100644 --- a/dom/html/HTMLVideoElement.cpp +++ b/dom/html/HTMLVideoElement.cpp @@ -217,9 +217,9 @@ void HTMLVideoElement::UnbindFromTree(bool aNullParent) { if (mVisualCloneSource) { mVisualCloneSource->EndCloningVisually(); } else if (mVisualCloneTarget) { - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("MozStopPictureInPicture"), CanBubble::eNo, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"MozStopPictureInPicture"_ns, + CanBubble::eNo, ChromeOnlyDispatch::eYes); asyncDispatcher->RunDOMEventWhenSafe(); EndCloningVisually(); @@ -236,7 +236,7 @@ nsresult HTMLVideoElement::SetAcceptHeader(nsIHttpChannel* aChannel) { "application/ogg;q=0.7," "audio/*;q=0.6,*/*;q=0.5"); - return aChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), value, false); + return aChannel->SetRequestHeader("Accept"_ns, value, false); } bool HTMLVideoElement::IsInteractiveHTMLContent() const { @@ -409,7 +409,7 @@ void HTMLVideoElement::CreateVideoWakeLockIfNeeded() { NS_ENSURE_TRUE_VOID(pmService); ErrorResult rv; - mScreenWakeLock = pmService->NewWakeLock(NS_LITERAL_STRING("video-playing"), + mScreenWakeLock = pmService->NewWakeLock(u"video-playing"_ns, OwnerDoc()->GetInnerWindow(), rv); } } diff --git a/dom/html/ImageDocument.cpp b/dom/html/ImageDocument.cpp index 06d978e96126..26821c64c33c 100644 --- a/dom/html/ImageDocument.cpp +++ b/dom/html/ImageDocument.cpp @@ -188,8 +188,8 @@ nsresult ImageDocument::StartDocumentLoad(const char* aCommand, void ImageDocument::Destroy() { if (RefPtr img = std::move(mImageContent)) { // Remove our event listener from the image content. - img->RemoveEventListener(NS_LITERAL_STRING("load"), this, false); - img->RemoveEventListener(NS_LITERAL_STRING("click"), this, false); + img->RemoveEventListener(u"load"_ns, this, false); + img->RemoveEventListener(u"click"_ns, this, false); // Break reference cycle with mImageContent, if we have one if (mObservingImageLoader) { @@ -207,8 +207,8 @@ void ImageDocument::SetScriptGlobalObject( nsCOMPtr target; if (mScriptGlobalObject && aScriptGlobalObject != mScriptGlobalObject) { target = do_QueryInterface(mScriptGlobalObject); - target->RemoveEventListener(NS_LITERAL_STRING("resize"), this, false); - target->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, false); + target->RemoveEventListener(u"resize"_ns, this, false); + target->RemoveEventListener(u"keypress"_ns, this, false); } // Set the script global object on the superclass before doing @@ -226,22 +226,21 @@ void ImageDocument::SetScriptGlobalObject( NS_ASSERTION(NS_SUCCEEDED(rv), "failed to create synthetic document"); target = mImageContent; - target->AddEventListener(NS_LITERAL_STRING("load"), this, false); - target->AddEventListener(NS_LITERAL_STRING("click"), this, false); + target->AddEventListener(u"load"_ns, this, false); + target->AddEventListener(u"click"_ns, this, false); } target = do_QueryInterface(aScriptGlobalObject); - target->AddEventListener(NS_LITERAL_STRING("resize"), this, false); - target->AddEventListener(NS_LITERAL_STRING("keypress"), this, false); + target->AddEventListener(u"resize"_ns, this, false); + target->AddEventListener(u"keypress"_ns, this, false); if (!InitialSetupHasBeenDone()) { - LinkStylesheet( - NS_LITERAL_STRING("resource://content-accessible/ImageDocument.css")); + LinkStylesheet(u"resource://content-accessible/ImageDocument.css"_ns); if (!nsContentUtils::IsChildOfSameType(this)) { - LinkStylesheet(NS_LITERAL_STRING( - "resource://content-accessible/TopLevelImageDocument.css")); - LinkStylesheet(NS_LITERAL_STRING( - "chrome://global/skin/media/TopLevelImageDocument.css")); + LinkStylesheet(nsLiteralString( + u"resource://content-accessible/TopLevelImageDocument.css")); + LinkStylesheet(nsLiteralString( + u"chrome://global/skin/media/TopLevelImageDocument.css")); } InitialSetupDone(); } @@ -280,10 +279,9 @@ void ImageDocument::ShrinkToFit() { uint32_t imageHeight = img->Height(); nsDOMTokenList* classList = img->ClassList(); if (imageHeight > mVisibleHeight) { - classList->Add(NS_LITERAL_STRING("overflowingVertical"), IgnoreErrors()); + classList->Add(u"overflowingVertical"_ns, IgnoreErrors()); } else { - classList->Remove(NS_LITERAL_STRING("overflowingVertical"), - IgnoreErrors()); + classList->Remove(u"overflowingVertical"_ns, IgnoreErrors()); } return; } @@ -406,30 +404,28 @@ void ImageDocument::OnHasTransparency() { } nsDOMTokenList* classList = mImageContent->ClassList(); - classList->Add(NS_LITERAL_STRING("transparent"), IgnoreErrors()); + classList->Add(u"transparent"_ns, IgnoreErrors()); } void ImageDocument::SetModeClass(eModeClasses mode) { nsDOMTokenList* classList = mImageContent->ClassList(); if (mode == eShrinkToFit) { - classList->Add(NS_LITERAL_STRING("shrinkToFit"), IgnoreErrors()); + classList->Add(u"shrinkToFit"_ns, IgnoreErrors()); } else { - classList->Remove(NS_LITERAL_STRING("shrinkToFit"), IgnoreErrors()); + classList->Remove(u"shrinkToFit"_ns, IgnoreErrors()); } if (mode == eOverflowingVertical) { - classList->Add(NS_LITERAL_STRING("overflowingVertical"), IgnoreErrors()); + classList->Add(u"overflowingVertical"_ns, IgnoreErrors()); } else { - classList->Remove(NS_LITERAL_STRING("overflowingVertical"), IgnoreErrors()); + classList->Remove(u"overflowingVertical"_ns, IgnoreErrors()); } if (mode == eOverflowingHorizontalOnly) { - classList->Add(NS_LITERAL_STRING("overflowingHorizontalOnly"), - IgnoreErrors()); + classList->Add(u"overflowingHorizontalOnly"_ns, IgnoreErrors()); } else { - classList->Remove(NS_LITERAL_STRING("overflowingHorizontalOnly"), - IgnoreErrors()); + classList->Remove(u"overflowingHorizontalOnly"_ns, IgnoreErrors()); } } @@ -639,8 +635,7 @@ void ImageDocument::UpdateTitleAndCharset() { mimeType.BeginReading(start); mimeType.EndReading(end); nsCString::const_iterator iter = end; - if (FindInReadable(NS_LITERAL_CSTRING("IMAGE/"), start, iter) && - iter != end) { + if (FindInReadable("IMAGE/"_ns, start, iter) && iter != end) { // strip out "X-" if any if (*iter == 'X') { ++iter; diff --git a/dom/html/MediaDocument.cpp b/dom/html/MediaDocument.cpp index f5ad3700552b..700c6dd4051b 100644 --- a/dom/html/MediaDocument.cpp +++ b/dom/html/MediaDocument.cpp @@ -209,12 +209,11 @@ nsresult MediaDocument::CreateSyntheticDocument() { RefPtr metaContent = NS_NewHTMLMetaElement(nodeInfo.forget()); NS_ENSURE_TRUE(metaContent, NS_ERROR_OUT_OF_MEMORY); - metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, - NS_LITERAL_STRING("viewport"), true); + metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, u"viewport"_ns, + true); - metaContent->SetAttr( - kNameSpaceID_None, nsGkAtoms::content, - NS_LITERAL_STRING("width=device-width; height=device-height;"), true); + metaContent->SetAttr(kNameSpaceID_None, nsGkAtoms::content, + u"width=device-width; height=device-height;"_ns, true); head->AppendChildTo(metaContent, false); root->AppendChildTo(head, false); @@ -287,8 +286,7 @@ nsresult MediaDocument::LinkStylesheet(const nsAString& aStylesheet) { RefPtr link = NS_NewHTMLLinkElement(nodeInfo.forget()); NS_ENSURE_TRUE(link, NS_ERROR_OUT_OF_MEMORY); - link->SetAttr(kNameSpaceID_None, nsGkAtoms::rel, - NS_LITERAL_STRING("stylesheet"), true); + link->SetAttr(kNameSpaceID_None, nsGkAtoms::rel, u"stylesheet"_ns, true); link->SetAttr(kNameSpaceID_None, nsGkAtoms::href, aStylesheet, true); @@ -305,8 +303,8 @@ nsresult MediaDocument::LinkScript(const nsAString& aScript) { NS_NewHTMLScriptElement(nodeInfo.forget()); NS_ENSURE_TRUE(script, NS_ERROR_OUT_OF_MEMORY); - script->SetAttr(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("text/javascript"), true); + script->SetAttr(kNameSpaceID_None, nsGkAtoms::type, u"text/javascript"_ns, + true); script->SetAttr(kNameSpaceID_None, nsGkAtoms::src, aScript, true); diff --git a/dom/html/MediaError.cpp b/dom/html/MediaError.cpp index 40733f0cc83e..2464bc76f47e 100644 --- a/dom/html/MediaError.cpp +++ b/dom/html/MediaError.cpp @@ -45,7 +45,7 @@ void MediaError::GetMessage(nsAString& aResult) const { // Print a warning message to JavaScript console to alert developers of // a non-whitelisted error message. nsAutoCString message = - NS_LITERAL_CSTRING( + nsLiteralCString( "This error message will be blank when " "privacy.resistFingerprinting = true." " If it is really necessary, please add it to the whitelist in" @@ -63,7 +63,7 @@ void MediaError::GetMessage(nsAString& aResult) const { // JavaScript console. nsContentUtils::ReportToConsoleNonLocalized( NS_ConvertASCIItoUTF16(message), nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("MediaError"), ownerDoc); + "MediaError"_ns, ownerDoc); } } diff --git a/dom/html/PluginDocument.cpp b/dom/html/PluginDocument.cpp index fedd0e34c4dc..cf86feb0bdc3 100644 --- a/dom/html/PluginDocument.cpp +++ b/dom/html/PluginDocument.cpp @@ -153,7 +153,7 @@ nsresult PluginDocument::StartDocumentLoad(const char* aCommand, nsCOMPtr dsti(do_QueryInterface(aContainer)); if (dsti) { bool isMsgPane = false; - dsti->NameEquals(NS_LITERAL_STRING("messagepane"), &isMsgPane); + dsti->NameEquals(u"messagepane"_ns, &isMsgPane); if (isMsgPane) { return NS_ERROR_FAILURE; } @@ -208,8 +208,8 @@ nsresult PluginDocument::CreateSyntheticPluginDocument() { NS_ENSURE_SUCCESS(rv, rv); // make it a named element - mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, - NS_LITERAL_STRING("plugin"), false); + mPluginContent->SetAttr(kNameSpaceID_None, nsGkAtoms::name, u"plugin"_ns, + false); // fill viewport and auto-resize NS_NAMED_LITERAL_STRING(percent100, "100%"); diff --git a/dom/html/TextControlState.cpp b/dom/html/TextControlState.cpp index 8b564e54cb76..fdbd0cb9ff88 100644 --- a/dom/html/TextControlState.cpp +++ b/dom/html/TextControlState.cpp @@ -865,7 +865,7 @@ void TextInputListener::OnSelectionChange(Selection& aSelection, return; } - UpdateTextInputCommands(NS_LITERAL_STRING("select"), &aSelection, aReason); + UpdateTextInputCommands(u"select"_ns, &aSelection, aReason); } MOZ_CAN_RUN_SCRIPT @@ -1009,7 +1009,7 @@ nsresult TextInputListener::OnEditActionHandled(TextEditor& aTextEditor) { if ((numUndoItems && !mHadUndoItems) || (!numUndoItems && mHadUndoItems) || (numRedoItems && !mHadRedoItems) || (!numRedoItems && mHadRedoItems)) { // Modify the menu if undo or redo items are different - UpdateTextInputCommands(NS_LITERAL_STRING("undo")); + UpdateTextInputCommands(u"undo"_ns); mHadUndoItems = numUndoItems != 0; mHadRedoItems = numRedoItems != 0; @@ -1642,11 +1642,9 @@ nsresult TextControlState::BindToFrame(nsTextControlFrame* aFrame) { // Set the correct direction on the newly created root node if (mTextEditor->IsRightToLeft()) { - rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, - NS_LITERAL_STRING("rtl"), false); + rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, u"rtl"_ns, false); } else if (mTextEditor->IsLeftToRight()) { - rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, - NS_LITERAL_STRING("ltr"), false); + rootNode->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, u"ltr"_ns, false); } else { // otherwise, inherit the content node's direction } @@ -2096,7 +2094,7 @@ void TextControlState::SetSelectionRange( if (changed) { // It sure would be nice if we had an existing Element* or so to work with. RefPtr asyncDispatcher = - new AsyncEventDispatcher(mTextCtrlElement, NS_LITERAL_STRING("select"), + new AsyncEventDispatcher(mTextCtrlElement, u"select"_ns, CanBubble::eYes, ChromeOnlyDispatch::eNo); asyncDispatcher->PostDOMEvent(); } @@ -2441,14 +2439,11 @@ void TextControlState::UnbindFromFrame(nsTextControlFrame* aFrame) { EventListenerManager* manager = mTextCtrlElement->GetExistingListenerManager(); if (manager) { - manager->RemoveEventListenerByType(mTextListener, - NS_LITERAL_STRING("keydown"), + manager->RemoveEventListenerByType(mTextListener, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); - manager->RemoveEventListenerByType(mTextListener, - NS_LITERAL_STRING("keypress"), + manager->RemoveEventListenerByType(mTextListener, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); - manager->RemoveEventListenerByType(mTextListener, - NS_LITERAL_STRING("keyup"), + manager->RemoveEventListenerByType(mTextListener, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); } @@ -3000,12 +2995,11 @@ void TextControlState::InitializeKeyboardEventListeners() { EventListenerManager* manager = mTextCtrlElement->GetOrCreateListenerManager(); if (manager) { - manager->AddEventListenerByType(mTextListener, NS_LITERAL_STRING("keydown"), + manager->AddEventListenerByType(mTextListener, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); - manager->AddEventListenerByType(mTextListener, - NS_LITERAL_STRING("keypress"), + manager->AddEventListenerByType(mTextListener, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); - manager->AddEventListenerByType(mTextListener, NS_LITERAL_STRING("keyup"), + manager->AddEventListenerByType(mTextListener, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); } diff --git a/dom/html/TextTrackManager.cpp b/dom/html/TextTrackManager.cpp index 324ab8fa8b00..0f52708c328a 100644 --- a/dom/html/TextTrackManager.cpp +++ b/dom/html/TextTrackManager.cpp @@ -310,14 +310,11 @@ void TextTrackManager::PopulatePendingList() { void TextTrackManager::AddListeners() { if (mMediaElement) { - mMediaElement->AddEventListener(NS_LITERAL_STRING("resizecaption"), this, - false, false); - mMediaElement->AddEventListener(NS_LITERAL_STRING("resizevideocontrols"), - this, false, false); - mMediaElement->AddEventListener(NS_LITERAL_STRING("seeked"), this, false, + mMediaElement->AddEventListener(u"resizecaption"_ns, this, false, false); + mMediaElement->AddEventListener(u"resizevideocontrols"_ns, this, false, false); - mMediaElement->AddEventListener(NS_LITERAL_STRING("controlbarchange"), this, - false, true); + mMediaElement->AddEventListener(u"seeked"_ns, this, false, false); + mMediaElement->AddEventListener(u"controlbarchange"_ns, this, false, true); } } @@ -762,7 +759,7 @@ void TextTrackManager::TimeMarchesOn() { WEBVTT_LOG("Prepare 'enter' event for cue %p [%f, %f] in missing cues", cue, cue->StartTime(), cue->EndTime()); SimpleTextTrackEvent* event = new SimpleTextTrackEvent( - NS_LITERAL_STRING("enter"), cue->StartTime(), cue->GetTrack(), cue); + u"enter"_ns, cue->StartTime(), cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), @@ -778,8 +775,8 @@ void TextTrackManager::TimeMarchesOn() { cue->StartTime() > cue->EndTime() ? cue->StartTime() : cue->EndTime(); WEBVTT_LOG("Prepare 'exit' event for cue %p [%f, %f] in other cues", cue, cue->StartTime(), cue->EndTime()); - SimpleTextTrackEvent* event = new SimpleTextTrackEvent( - NS_LITERAL_STRING("exit"), time, cue->GetTrack(), cue); + SimpleTextTrackEvent* event = + new SimpleTextTrackEvent(u"exit"_ns, time, cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), @@ -795,7 +792,7 @@ void TextTrackManager::TimeMarchesOn() { WEBVTT_LOG("Prepare 'enter' event for cue %p [%f, %f] in current cues", cue, cue->StartTime(), cue->EndTime()); SimpleTextTrackEvent* event = new SimpleTextTrackEvent( - NS_LITERAL_STRING("enter"), cue->StartTime(), cue->GetTrack(), cue); + u"enter"_ns, cue->StartTime(), cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), @@ -813,10 +810,10 @@ void TextTrackManager::TimeMarchesOn() { for (uint32_t i = 0; i < affectedTracks.Length(); ++i) { TextTrack* ttrack = affectedTracks[i]; if (ttrack) { - ttrack->DispatchAsyncTrustedEvent(NS_LITERAL_STRING("cuechange")); + ttrack->DispatchAsyncTrustedEvent(u"cuechange"_ns); HTMLTrackElement* trackElement = ttrack->GetTrackElement(); if (trackElement) { - trackElement->DispatchTrackRunnable(NS_LITERAL_STRING("cuechange")); + trackElement->DispatchTrackRunnable(u"cuechange"_ns); } } } diff --git a/dom/html/VideoDocument.cpp b/dom/html/VideoDocument.cpp index ca5d21ec5eb2..0987b848c8f3 100644 --- a/dom/html/VideoDocument.cpp +++ b/dom/html/VideoDocument.cpp @@ -90,12 +90,11 @@ void VideoDocument::SetScriptGlobalObject( NS_ASSERTION(NS_SUCCEEDED(rv), "failed to create synthetic video document"); if (!nsContentUtils::IsChildOfSameType(this)) { - LinkStylesheet(NS_LITERAL_STRING( - "resource://content-accessible/TopLevelVideoDocument.css")); - LinkStylesheet(NS_LITERAL_STRING( - "chrome://global/skin/media/TopLevelVideoDocument.css")); - LinkScript(NS_LITERAL_STRING( - "chrome://global/content/TopLevelVideoDocument.js")); + LinkStylesheet(nsLiteralString( + u"resource://content-accessible/TopLevelVideoDocument.css")); + LinkStylesheet(nsLiteralString( + u"chrome://global/skin/media/TopLevelVideoDocument.css")); + LinkScript(u"chrome://global/content/TopLevelVideoDocument.js"_ns); } InitialSetupDone(); } @@ -127,8 +126,8 @@ nsresult VideoDocument::CreateVideoElement() { // not have margins element->SetAttr( kNameSpaceID_None, nsGkAtoms::style, - NS_LITERAL_STRING( - "position:absolute; top:0; left:0; width:100%; height:100%"), + nsLiteralString( + u"position:absolute; top:0; left:0; width:100%; height:100%"), true); } diff --git a/dom/html/input/DateTimeInputTypes.cpp b/dom/html/input/DateTimeInputTypes.cpp index 27a9e9194b1f..555264e79705 100644 --- a/dom/html/input/DateTimeInputTypes.cpp +++ b/dom/html/input/DateTimeInputTypes.cpp @@ -92,8 +92,8 @@ bool DateTimeInputTypeBase::HasBadInput() const { return false; } - Element* editWrapperElement = mInputElement->GetShadowRoot()->GetElementById( - NS_LITERAL_STRING("edit-wrapper")); + Element* editWrapperElement = + mInputElement->GetShadowRoot()->GetElementById(u"edit-wrapper"_ns); if (!editWrapperElement) { return false; @@ -102,8 +102,7 @@ bool DateTimeInputTypeBase::HasBadInput() const { // Incomplete field does not imply bad input. for (Element* child = editWrapperElement->GetFirstElementChild(); child; child = child->GetNextElementSibling()) { - if (child->ClassList()->Contains( - NS_LITERAL_STRING("datetime-edit-field"))) { + if (child->ClassList()->Contains(u"datetime-edit-field"_ns)) { nsAutoString value; child->GetAttr(kNameSpaceID_None, nsGkAtoms::value, value); if (value.IsEmpty()) { @@ -142,7 +141,7 @@ nsresult DateTimeInputTypeBase::GetRangeUnderflowMessage(nsAString& aMessage) { nsresult DateTimeInputTypeBase::MinMaxStepAttrChanged() { if (Element* dateTimeBoxElement = mInputElement->GetDateTimeBoxElement()) { AsyncEventDispatcher* dispatcher = new AsyncEventDispatcher( - dateTimeBoxElement, NS_LITERAL_STRING("MozNotifyMinMaxStepAttrChanged"), + dateTimeBoxElement, u"MozNotifyMinMaxStepAttrChanged"_ns, CanBubble::eNo, ChromeOnlyDispatch::eNo); dispatcher->RunDOMEventWhenSafe(); } diff --git a/dom/html/nsDOMStringMap.cpp b/dom/html/nsDOMStringMap.cpp index 51979dd0e884..f9670ecb32d5 100644 --- a/dom/html/nsDOMStringMap.cpp +++ b/dom/html/nsDOMStringMap.cpp @@ -200,7 +200,7 @@ bool nsDOMStringMap::AttrToDataProp(const nsAString& aAttr, nsAutoString& aResult) { // If the attribute name does not begin with "data-" then it can not be // a data attribute. - if (!StringBeginsWith(aAttr, NS_LITERAL_STRING("data-"))) { + if (!StringBeginsWith(aAttr, u"data-"_ns)) { return false; } @@ -238,8 +238,7 @@ void nsDOMStringMap::AttributeChanged(Element* aElement, int32_t aNameSpaceID, if ((aModType == MutationEvent_Binding::ADDITION || aModType == MutationEvent_Binding::REMOVAL) && aNameSpaceID == kNameSpaceID_None && - StringBeginsWith(nsDependentAtomString(aAttribute), - NS_LITERAL_STRING("data-"))) { + StringBeginsWith(nsDependentAtomString(aAttribute), u"data-"_ns)) { ++mExpandoAndGeneration.generation; } } diff --git a/dom/html/nsGenericHTMLElement.cpp b/dom/html/nsGenericHTMLElement.cpp index 65984ae9950a..e93f844675f2 100644 --- a/dom/html/nsGenericHTMLElement.cpp +++ b/dom/html/nsGenericHTMLElement.cpp @@ -673,12 +673,11 @@ nsresult nsGenericHTMLElement::AfterSetAttr( SetDirectionalityOnDescendants(this, dir, aNotify); } else if (aName == nsGkAtoms::contenteditable) { int32_t editableCountDelta = 0; - if (aOldValue && - (aOldValue->Equals(NS_LITERAL_STRING("true"), eIgnoreCase) || - aOldValue->Equals(EmptyString(), eIgnoreCase))) { + if (aOldValue && (aOldValue->Equals(u"true"_ns, eIgnoreCase) || + aOldValue->Equals(EmptyString(), eIgnoreCase))) { editableCountDelta = -1; } - if (aValue && (aValue->Equals(NS_LITERAL_STRING("true"), eIgnoreCase) || + if (aValue && (aValue->Equals(u"true"_ns, eIgnoreCase) || aValue->Equals(EmptyString(), eIgnoreCase))) { ++editableCountDelta; } diff --git a/dom/html/nsGenericHTMLElement.h b/dom/html/nsGenericHTMLElement.h index 7f466f91a1c6..9e3c1dc80ecc 100644 --- a/dom/html/nsGenericHTMLElement.h +++ b/dom/html/nsGenericHTMLElement.h @@ -99,10 +99,8 @@ class nsGenericHTMLElement : public nsGenericHTMLElementBase { nsGkAtoms::_true, eIgnoreCase); } void SetDraggable(bool aDraggable, mozilla::ErrorResult& aError) { - SetHTMLAttr( - nsGkAtoms::draggable, - aDraggable ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"), - aError); + SetHTMLAttr(nsGkAtoms::draggable, aDraggable ? u"true"_ns : u"false"_ns, + aError); } void GetContentEditable(nsString& aContentEditable) { ContentEditableTristate value = GetContentEditableValue(); @@ -119,11 +117,9 @@ class nsGenericHTMLElement : public nsGenericHTMLElementBase { if (aContentEditable.LowerCaseEqualsLiteral("inherit")) { UnsetHTMLAttr(nsGkAtoms::contenteditable, aError); } else if (aContentEditable.LowerCaseEqualsLiteral("true")) { - SetHTMLAttr(nsGkAtoms::contenteditable, NS_LITERAL_STRING("true"), - aError); + SetHTMLAttr(nsGkAtoms::contenteditable, u"true"_ns, aError); } else if (aContentEditable.LowerCaseEqualsLiteral("false")) { - SetHTMLAttr(nsGkAtoms::contenteditable, NS_LITERAL_STRING("false"), - aError); + SetHTMLAttr(nsGkAtoms::contenteditable, u"false"_ns, aError); } else { aError.Throw(NS_ERROR_DOM_SYNTAX_ERR); } @@ -162,10 +158,8 @@ class nsGenericHTMLElement : public nsGenericHTMLElementBase { mozilla::dom::HTMLMenuElement* GetContextMenu() const; bool Spellcheck(); void SetSpellcheck(bool aSpellcheck, mozilla::ErrorResult& aError) { - SetHTMLAttr( - nsGkAtoms::spellcheck, - aSpellcheck ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"), - aError); + SetHTMLAttr(nsGkAtoms::spellcheck, aSpellcheck ? u"true"_ns : u"false"_ns, + aError); } MOZ_CAN_RUN_SCRIPT diff --git a/dom/html/nsIConstraintValidation.cpp b/dom/html/nsIConstraintValidation.cpp index 9406297eb49f..4675343339bd 100644 --- a/dom/html/nsIConstraintValidation.cpp +++ b/dom/html/nsIConstraintValidation.cpp @@ -89,8 +89,8 @@ bool nsIConstraintValidation::CheckValidity() { "This class should be inherited by HTML elements only!"); nsContentUtils::DispatchTrustedEvent(content->OwnerDoc(), content, - NS_LITERAL_STRING("invalid"), - CanBubble::eNo, Cancelable::eYes); + u"invalid"_ns, CanBubble::eNo, + Cancelable::eYes); return false; } @@ -111,9 +111,9 @@ bool nsIConstraintValidation::ReportValidity() { MOZ_ASSERT(element, "This class should be inherited by HTML elements only!"); bool defaultAction = true; - nsContentUtils::DispatchTrustedEvent( - element->OwnerDoc(), element, NS_LITERAL_STRING("invalid"), - CanBubble::eNo, Cancelable::eYes, &defaultAction); + nsContentUtils::DispatchTrustedEvent(element->OwnerDoc(), element, + u"invalid"_ns, CanBubble::eNo, + Cancelable::eYes, &defaultAction); if (!defaultAction) { return false; } @@ -132,7 +132,7 @@ bool nsIConstraintValidation::ReportValidity() { RefPtr event = NS_NewDOMCustomEvent(element->OwnerDoc(), nullptr, nullptr); - event->InitCustomEvent(jsapi.cx(), NS_LITERAL_STRING("MozInvalidForm"), + event->InitCustomEvent(jsapi.cx(), u"MozInvalidForm"_ns, /* CanBubble */ true, /* Cancelable */ true, detail); event->SetTrusted(true); diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp index 9d422838e74d..0dbd2fc50de6 100644 --- a/dom/indexedDB/ActorsParent.cpp +++ b/dom/indexedDB/ActorsParent.cpp @@ -919,28 +919,28 @@ nsresult CreateFileTables(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("CreateFileTables", DOM); // Table `file` - nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE file (" - "id INTEGER PRIMARY KEY, " - "refcount INTEGER NOT NULL" - ");")); + nsresult rv = + aConnection.ExecuteSimpleSQL(nsLiteralCString("CREATE TABLE file (" + "id INTEGER PRIMARY KEY, " + "refcount INTEGER NOT NULL" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_insert_trigger " - "AFTER INSERT ON object_data " - "FOR EACH ROW " - "WHEN NEW.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(NULL, NEW.file_ids); " - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_insert_trigger " + "AFTER INSERT ON object_data " + "FOR EACH ROW " + "WHEN NEW.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(NULL, NEW.file_ids); " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TRIGGER object_data_update_trigger " "AFTER UPDATE OF file_ids ON object_data " "FOR EACH ROW " @@ -953,23 +953,23 @@ nsresult CreateFileTables(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_delete_trigger " - "AFTER DELETE ON object_data " - "FOR EACH ROW WHEN OLD.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(OLD.file_ids, NULL); " - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_delete_trigger " + "AFTER DELETE ON object_data " + "FOR EACH ROW WHEN OLD.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(OLD.file_ids, NULL); " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER file_update_trigger " - "AFTER UPDATE ON file " - "FOR EACH ROW WHEN NEW.refcount = 0 " - "BEGIN " - "DELETE FROM file WHERE id = OLD.id; " - "END;")); + nsLiteralCString("CREATE TRIGGER file_update_trigger " + "AFTER UPDATE ON file " + "FOR EACH ROW WHEN NEW.refcount = 0 " + "BEGIN " + "DELETE FROM file WHERE id = OLD.id; " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -991,83 +991,83 @@ nsresult CreateTables(mozIStorageConnection& aConnection) { // directory can figure out the origin of every db without having to // reverse-engineer our hash scheme. nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE database" - "( name TEXT PRIMARY KEY" - ", origin TEXT NOT NULL" - ", version INTEGER NOT NULL DEFAULT 0" - ", last_vacuum_time INTEGER NOT NULL DEFAULT 0" - ", last_analyze_time INTEGER NOT NULL DEFAULT 0" - ", last_vacuum_size INTEGER NOT NULL DEFAULT 0" - ") WITHOUT ROWID;")); + nsLiteralCString("CREATE TABLE database" + "( name TEXT PRIMARY KEY" + ", origin TEXT NOT NULL" + ", version INTEGER NOT NULL DEFAULT 0" + ", last_vacuum_time INTEGER NOT NULL DEFAULT 0" + ", last_analyze_time INTEGER NOT NULL DEFAULT 0" + ", last_vacuum_size INTEGER NOT NULL DEFAULT 0" + ") WITHOUT ROWID;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `object_store` rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE object_store" - "( id INTEGER PRIMARY KEY" - ", auto_increment INTEGER NOT NULL DEFAULT 0" - ", name TEXT NOT NULL" - ", key_path TEXT" - ");")); + nsLiteralCString("CREATE TABLE object_store" + "( id INTEGER PRIMARY KEY" + ", auto_increment INTEGER NOT NULL DEFAULT 0" + ", name TEXT NOT NULL" + ", key_path TEXT" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `object_store_index` rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE object_store_index" - "( id INTEGER PRIMARY KEY" - ", object_store_id INTEGER NOT NULL" - ", name TEXT NOT NULL" - ", key_path TEXT NOT NULL" - ", unique_index INTEGER NOT NULL" - ", multientry INTEGER NOT NULL" - ", locale TEXT" - ", is_auto_locale BOOLEAN NOT NULL" - ", FOREIGN KEY (object_store_id) " - "REFERENCES object_store(id) " - ");")); + nsLiteralCString("CREATE TABLE object_store_index" + "( id INTEGER PRIMARY KEY" + ", object_store_id INTEGER NOT NULL" + ", name TEXT NOT NULL" + ", key_path TEXT NOT NULL" + ", unique_index INTEGER NOT NULL" + ", multientry INTEGER NOT NULL" + ", locale TEXT" + ", is_auto_locale BOOLEAN NOT NULL" + ", FOREIGN KEY (object_store_id) " + "REFERENCES object_store(id) " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `object_data` rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE object_data" - "( object_store_id INTEGER NOT NULL" - ", key BLOB NOT NULL" - ", index_data_values BLOB DEFAULT NULL" - ", file_ids TEXT" - ", data BLOB NOT NULL" - ", PRIMARY KEY (object_store_id, key)" - ", FOREIGN KEY (object_store_id) " - "REFERENCES object_store(id) " - ") WITHOUT ROWID;")); + nsLiteralCString("CREATE TABLE object_data" + "( object_store_id INTEGER NOT NULL" + ", key BLOB NOT NULL" + ", index_data_values BLOB DEFAULT NULL" + ", file_ids TEXT" + ", data BLOB NOT NULL" + ", PRIMARY KEY (object_store_id, key)" + ", FOREIGN KEY (object_store_id) " + "REFERENCES object_store(id) " + ") WITHOUT ROWID;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `index_data` rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE index_data" - "( index_id INTEGER NOT NULL" - ", value BLOB NOT NULL" - ", object_data_key BLOB NOT NULL" - ", object_store_id INTEGER NOT NULL" - ", value_locale BLOB" - ", PRIMARY KEY (index_id, value, object_data_key)" - ", FOREIGN KEY (index_id) " - "REFERENCES object_store_index(id) " - ", FOREIGN KEY (object_store_id, object_data_key) " - "REFERENCES object_data(object_store_id, key) " - ") WITHOUT ROWID;")); + nsLiteralCString("CREATE TABLE index_data" + "( index_id INTEGER NOT NULL" + ", value BLOB NOT NULL" + ", object_data_key BLOB NOT NULL" + ", object_store_id INTEGER NOT NULL" + ", value_locale BLOB" + ", PRIMARY KEY (index_id, value, object_data_key)" + ", FOREIGN KEY (index_id) " + "REFERENCES object_store_index(id) " + ", FOREIGN KEY (object_store_id, object_data_key) " + "REFERENCES object_data(object_store_id, key) " + ") WITHOUT ROWID;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX index_data_value_locale_index " "ON index_data (index_id, value_locale, object_data_key, value) " "WHERE value_locale IS NOT NULL;")); @@ -1077,23 +1077,23 @@ nsresult CreateTables(mozIStorageConnection& aConnection) { // Table `unique_index_data` rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE unique_index_data" - "( index_id INTEGER NOT NULL" - ", value BLOB NOT NULL" - ", object_store_id INTEGER NOT NULL" - ", object_data_key BLOB NOT NULL" - ", value_locale BLOB" - ", PRIMARY KEY (index_id, value)" - ", FOREIGN KEY (index_id) " - "REFERENCES object_store_index(id) " - ", FOREIGN KEY (object_store_id, object_data_key) " - "REFERENCES object_data(object_store_id, key) " - ") WITHOUT ROWID;")); + nsLiteralCString("CREATE TABLE unique_index_data" + "( index_id INTEGER NOT NULL" + ", value BLOB NOT NULL" + ", object_store_id INTEGER NOT NULL" + ", object_data_key BLOB NOT NULL" + ", value_locale BLOB" + ", PRIMARY KEY (index_id, value)" + ", FOREIGN KEY (index_id) " + "REFERENCES object_store_index(id) " + ", FOREIGN KEY (object_store_id, object_data_key) " + "REFERENCES object_data(object_store_id, key) " + ") WITHOUT ROWID;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX unique_index_data_value_locale_index " "ON unique_index_data (index_id, value_locale, object_data_key, value) " "WHERE value_locale IS NOT NULL;")); @@ -1125,8 +1125,8 @@ nsresult UpgradeSchemaFrom4To5(mozIStorageConnection& aConnection) { // convert that to an integer, and if we fail, set it to 0. nsCOMPtr stmt; rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT name, version, dataVersion " - "FROM database"), + nsLiteralCString("SELECT name, version, dataVersion " + "FROM database"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -1170,17 +1170,17 @@ nsresult UpgradeSchemaFrom4To5(mozIStorageConnection& aConnection) { } } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE database")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE database"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE database (" - "name TEXT NOT NULL, " - "version INTEGER NOT NULL DEFAULT 0, " - "dataVersion INTEGER NOT NULL" - ");")); + nsLiteralCString("CREATE TABLE database (" + "name TEXT NOT NULL, " + "version INTEGER NOT NULL DEFAULT 0, " + "dataVersion INTEGER NOT NULL" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1188,8 +1188,8 @@ nsresult UpgradeSchemaFrom4To5(mozIStorageConnection& aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO database (name, version, dataVersion) " - "VALUES (:name, :version, :dataVersion)"), + nsLiteralCString("INSERT INTO database (name, version, dataVersion) " + "VALUES (:name, :version, :dataVersion)"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -1233,26 +1233,22 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom5To6", DOM); // First, drop all the indexes we're no longer going to use. - nsresult rv = - aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP INDEX key_index;")); + nsresult rv = aConnection.ExecuteSimpleSQL("DROP INDEX key_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX ai_key_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP INDEX ai_key_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX value_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP INDEX value_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX ai_value_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP INDEX ai_value_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1261,31 +1257,30 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // this by copying into a temporary table, dropping the original, then copying // back into a newly created table. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id INTEGER PRIMARY KEY, " - "object_store_id, " - "key_value, " - "data " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id INTEGER PRIMARY KEY, " + "object_store_id, " + "key_value, " + "data " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT id, object_store_id, key_value, data " - "FROM object_data;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT id, object_store_id, key_value, data " + "FROM object_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE object_data (" "id INTEGER PRIMARY KEY, " "object_store_id INTEGER NOT NULL, " @@ -1300,15 +1295,14 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO object_data " - "SELECT id, object_store_id, key_value, data " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT INTO object_data " + "SELECT id, object_store_id, key_value, data " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1316,30 +1310,29 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // We need to add a unique constraint to our ai_object_data table. Copy all // the data out of it using a temporary table as before. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id INTEGER PRIMARY KEY, " - "object_store_id, " - "data " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id INTEGER PRIMARY KEY, " + "object_store_id, " + "data " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT id, object_store_id, data " - "FROM ai_object_data;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT id, object_store_id, data " + "FROM ai_object_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_object_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_object_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE ai_object_data (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "object_store_id INTEGER NOT NULL, " @@ -1353,15 +1346,14 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO ai_object_data " - "SELECT id, object_store_id, data " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT INTO ai_object_data " + "SELECT id, object_store_id, data " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1369,17 +1361,17 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // Fix up the index_data table. We're reordering the columns as well as // changing the primary key from being a simple id to being a composite. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "object_data_key, " - "object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "object_data_key, " + "object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO temp_upgrade " "SELECT index_id, value, object_data_key, object_data_id " "FROM index_data;")); @@ -1387,13 +1379,12 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE index_data (" "index_id INTEGER NOT NULL, " "value NOT NULL, " @@ -1409,7 +1400,7 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO index_data " "SELECT index_id, value, object_data_key, object_data_id " "FROM temp_upgrade;")); @@ -1417,15 +1408,14 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX index_data_object_data_id_index " - "ON index_data (object_data_id);")); + nsLiteralCString("CREATE INDEX index_data_object_data_id_index " + "ON index_data (object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1433,17 +1423,17 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // Fix up the unique_index_data table. We're reordering the columns as well as // changing the primary key from being a simple id to being a composite. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "object_data_key, " - "object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "object_data_key, " + "object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO temp_upgrade " "SELECT index_id, value, object_data_key, object_data_id " "FROM unique_index_data;")); @@ -1451,13 +1441,12 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE unique_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE unique_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE unique_index_data (" "index_id INTEGER NOT NULL, " "value NOT NULL, " @@ -1474,7 +1463,7 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO unique_index_data " "SELECT index_id, value, object_data_key, object_data_id " "FROM temp_upgrade;")); @@ -1482,15 +1471,14 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX unique_index_data_object_data_id_index " - "ON unique_index_data (object_data_id);")); + nsLiteralCString("CREATE INDEX unique_index_data_object_data_id_index " + "ON unique_index_data (object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1498,30 +1486,29 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // Fix up the ai_index_data table. We're reordering the columns as well as // changing the primary key from being a simple id to being a composite. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "ai_object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "ai_object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT index_id, value, ai_object_data_id " - "FROM ai_index_data;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT index_id, value, ai_object_data_id " + "FROM ai_index_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE ai_index_data (" "index_id INTEGER NOT NULL, " "value NOT NULL, " @@ -1537,22 +1524,21 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT OR IGNORE INTO ai_index_data " - "SELECT index_id, value, ai_object_data_id " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT OR IGNORE INTO ai_index_data " + "SELECT index_id, value, ai_object_data_id " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX ai_index_data_ai_object_data_id_index " - "ON ai_index_data (ai_object_data_id);")); + nsLiteralCString("CREATE INDEX ai_index_data_ai_object_data_id_index " + "ON ai_index_data (ai_object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1560,30 +1546,29 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { // Fix up the ai_unique_index_data table. We're reordering the columns as well // as changing the primary key from being a simple id to being a composite. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "ai_object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "ai_object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT index_id, value, ai_object_data_id " - "FROM ai_unique_index_data;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT index_id, value, ai_object_data_id " + "FROM ai_unique_index_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_unique_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_unique_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE ai_unique_index_data (" "index_id INTEGER NOT NULL, " "value NOT NULL, " @@ -1600,20 +1585,19 @@ nsresult UpgradeSchemaFrom5To6(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO ai_unique_index_data " - "SELECT index_id, value, ai_object_data_id " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT INTO ai_unique_index_data " + "SELECT index_id, value, ai_object_data_id " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX ai_unique_index_data_ai_object_data_id_index " "ON ai_unique_index_data (ai_object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -1634,52 +1618,50 @@ nsresult UpgradeSchemaFrom6To7(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom6To7", DOM); nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id, " - "name, " - "key_path, " - "auto_increment" - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id, " + "name, " + "key_path, " + "auto_increment" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT id, name, key_path, auto_increment " - "FROM object_store;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT id, name, key_path, auto_increment " + "FROM object_store;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_store;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_store;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE object_store (" - "id INTEGER PRIMARY KEY, " - "auto_increment INTEGER NOT NULL DEFAULT 0, " - "name TEXT NOT NULL, " - "key_path TEXT, " - "UNIQUE (name)" - ");")); + nsLiteralCString("CREATE TABLE object_store (" + "id INTEGER PRIMARY KEY, " + "auto_increment INTEGER NOT NULL DEFAULT 0, " + "name TEXT NOT NULL, " + "key_path TEXT, " + "UNIQUE (name)" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "INSERT INTO object_store " - "SELECT id, auto_increment, name, nullif(key_path, '') " - "FROM temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL( + nsLiteralCString("INSERT INTO object_store " + "SELECT id, auto_increment, name, nullif(key_path, '') " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1698,34 +1680,33 @@ nsresult UpgradeSchemaFrom7To8(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom7To8", DOM); nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id, " - "object_store_id, " - "name, " - "key_path, " - "unique_index, " - "object_store_autoincrement" - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id, " + "object_store_id, " + "name, " + "key_path, " + "unique_index, " + "object_store_autoincrement" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT id, object_store_id, name, key_path, " - "unique_index, object_store_autoincrement " - "FROM object_store_index;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT id, object_store_id, name, key_path, " + "unique_index, object_store_autoincrement " + "FROM object_store_index;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_store_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_store_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE object_store_index (" "id INTEGER, " "object_store_id INTEGER NOT NULL, " @@ -1744,16 +1725,15 @@ nsresult UpgradeSchemaFrom7To8(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO object_store_index " - "SELECT id, object_store_id, name, key_path, " - "unique_index, 0, object_store_autoincrement " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT INTO object_store_index " + "SELECT id, object_store_id, name, key_path, " + "unique_index, 0, object_store_autoincrement " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1837,8 +1817,8 @@ nsresult UpgradeSchemaFrom8To9_0(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom8To9_0", DOM); // We no longer use the dataVersion column. - nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE database SET dataVersion = 0;")); + nsresult rv = + aConnection.ExecuteSimpleSQL("UPDATE database SET dataVersion = 0;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1854,13 +1834,13 @@ nsresult UpgradeSchemaFrom8To9_0(mozIStorageConnection& aConnection) { // Turn off foreign key constraints before we do anything here. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE object_data SET data = compress(data);")); + "UPDATE object_data SET data = compress(data);"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE ai_object_data SET data = compress(data);")); + "UPDATE ai_object_data SET data = compress(data);"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1884,13 +1864,13 @@ nsresult UpgradeSchemaFrom9_0To10_0(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom9_0To10_0", DOM); nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE object_data ADD COLUMN file_ids TEXT;")); + "ALTER TABLE object_data ADD COLUMN file_ids TEXT;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "ALTER TABLE ai_object_data ADD COLUMN file_ids TEXT;")); + rv = aConnection.ExecuteSimpleSQL( + "ALTER TABLE ai_object_data ADD COLUMN file_ids TEXT;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1914,34 +1894,33 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom10_0To11_0", DOM); nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id, " - "object_store_id, " - "name, " - "key_path, " - "unique_index, " - "multientry" - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id, " + "object_store_id, " + "name, " + "key_path, " + "unique_index, " + "multientry" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO temp_upgrade " - "SELECT id, object_store_id, name, key_path, " - "unique_index, multientry " - "FROM object_store_index;")); + nsLiteralCString("INSERT INTO temp_upgrade " + "SELECT id, object_store_id, name, key_path, " + "unique_index, multientry " + "FROM object_store_index;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_store_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_store_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE object_store_index (" "id INTEGER PRIMARY KEY, " "object_store_id INTEGER NOT NULL, " @@ -1958,27 +1937,26 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO object_store_index " - "SELECT id, object_store_id, name, key_path, " - "unique_index, multientry " - "FROM temp_upgrade;")); + nsLiteralCString("INSERT INTO object_store_index " + "SELECT id, object_store_id, name, key_path, " + "unique_index, multientry " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER object_data_insert_trigger;")); + "DROP TRIGGER object_data_insert_trigger;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO object_data (object_store_id, key_value, data, file_ids) " "SELECT object_store_id, id, data, file_ids " "FROM ai_object_data;")); @@ -1987,18 +1965,18 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_insert_trigger " - "AFTER INSERT ON object_data " - "FOR EACH ROW " - "WHEN NEW.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(NULL, NEW.file_ids); " - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_insert_trigger " + "AFTER INSERT ON object_data " + "FOR EACH ROW " + "WHEN NEW.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(NULL, NEW.file_ids); " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO index_data (index_id, value, object_data_key, " "object_data_id) " "SELECT ai_index_data.index_id, ai_index_data.value, " @@ -2013,7 +1991,7 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO unique_index_data (index_id, value, object_data_key, " "object_data_id) " "SELECT ai_unique_index_data.index_id, ai_unique_index_data.value, " @@ -2028,7 +2006,7 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "UPDATE object_store " "SET auto_increment = (SELECT max(id) FROM ai_object_data) + 1 " "WHERE auto_increment;")); @@ -2036,20 +2014,17 @@ nsresult UpgradeSchemaFrom10_0To11_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_unique_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_unique_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE ai_object_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE ai_object_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2139,18 +2114,18 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "id INTEGER PRIMARY KEY, " - "object_store_id, " - "key_value, " - "data, " - "file_ids " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "id INTEGER PRIMARY KEY, " + "object_store_id, " + "key_value, " + "data, " + "file_ids " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO temp_upgrade " "SELECT id, object_store_id, encode(key_value), data, file_ids " "FROM object_data;")); @@ -2158,13 +2133,12 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE object_data (" "id INTEGER PRIMARY KEY, " "object_store_id INTEGER NOT NULL, " @@ -2179,33 +2153,32 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "INSERT INTO object_data " - "SELECT id, object_store_id, key_value, file_ids, data " - "FROM temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL( + nsLiteralCString("INSERT INTO object_data " + "SELECT id, object_store_id, key_value, file_ids, data " + "FROM temp_upgrade;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_insert_trigger " - "AFTER INSERT ON object_data " - "FOR EACH ROW " - "WHEN NEW.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(NULL, NEW.file_ids); " - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_insert_trigger " + "AFTER INSERT ON object_data " + "FOR EACH ROW " + "WHEN NEW.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(NULL, NEW.file_ids); " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TRIGGER object_data_update_trigger " "AFTER UPDATE OF file_ids ON object_data " "FOR EACH ROW " @@ -2218,28 +2191,28 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_delete_trigger " - "AFTER DELETE ON object_data " - "FOR EACH ROW WHEN OLD.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(OLD.file_ids, NULL); " - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_delete_trigger " + "AFTER DELETE ON object_data " + "FOR EACH ROW WHEN OLD.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(OLD.file_ids, NULL); " + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "object_data_key, " - "object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "object_data_key, " + "object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO temp_upgrade " "SELECT index_id, encode(value), encode(object_data_key), object_data_id " "FROM index_data;")); @@ -2247,13 +2220,12 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE index_data (" "index_id INTEGER NOT NULL, " "value BLOB NOT NULL, " @@ -2269,7 +2241,7 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO index_data " "SELECT index_id, value, object_data_key, object_data_id " "FROM temp_upgrade;")); @@ -2277,31 +2249,30 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX index_data_object_data_id_index " - "ON index_data (object_data_id);")); + nsLiteralCString("CREATE INDEX index_data_object_data_id_index " + "ON index_data (object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMPORARY TABLE temp_upgrade (" - "index_id, " - "value, " - "object_data_key, " - "object_data_id " - ");")); + nsLiteralCString("CREATE TEMPORARY TABLE temp_upgrade (" + "index_id, " + "value, " + "object_data_key, " + "object_data_id " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO temp_upgrade " "SELECT index_id, encode(value), encode(object_data_key), object_data_id " "FROM unique_index_data;")); @@ -2309,13 +2280,12 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE unique_index_data;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE unique_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE unique_index_data (" "index_id INTEGER NOT NULL, " "value BLOB NOT NULL, " @@ -2332,7 +2302,7 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO unique_index_data " "SELECT index_id, value, object_data_key, object_data_id " "FROM temp_upgrade;")); @@ -2340,15 +2310,14 @@ nsresult UpgradeSchemaFrom11_0To12_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE temp_upgrade;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE temp_upgrade;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX unique_index_data_object_data_id_index " - "ON unique_index_data (object_data_id);")); + nsLiteralCString("CREATE INDEX unique_index_data_object_data_id_index " + "ON unique_index_data (object_data_id);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2816,7 +2785,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( mozIStorageConnection& aConnection, const nsACString& aOrigin) { MOZ_ASSERT(!aOrigin.IsEmpty()); - nsresult rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Drop these triggers to avoid unnecessary work during the upgrade // process. "DROP TRIGGER object_data_insert_trigger;" @@ -2826,7 +2795,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Drop these indexes before we do anything else to free disk space. "DROP INDEX index_data_object_data_id_index;" "DROP INDEX unique_index_data_object_data_id_index;")); @@ -2836,7 +2805,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Create the new tables and triggers first. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |database| table. "CREATE TABLE database_upgrade " "( name TEXT PRIMARY KEY" @@ -2850,7 +2819,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |object_store| table. "CREATE TABLE object_store_upgrade" "( id INTEGER PRIMARY KEY" @@ -2862,7 +2831,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |object_store_index| table. "CREATE TABLE object_store_index_upgrade" "( id INTEGER PRIMARY KEY" @@ -2878,7 +2847,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |object_data| table. "CREATE TABLE object_data_upgrade" "( object_store_id INTEGER NOT NULL" @@ -2894,7 +2863,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |index_data| table. "CREATE TABLE index_data_upgrade" "( index_id INTEGER NOT NULL" @@ -2911,7 +2880,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // This will eventually become the |unique_index_data| table. "CREATE TABLE unique_index_data_upgrade" "( index_id INTEGER NOT NULL" @@ -2928,7 +2897,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Temporarily store |index_data_values| that we build during the upgrade // of the index tables. We will later move this to the |object_data| // table. @@ -2942,7 +2911,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // These two triggers help build the |index_data_values| blobs. The nested // SELECT statements help us achieve an "INSERT OR UPDATE"-like behavior. "CREATE TEMPORARY TRIGGER unique_index_data_upgrade_insert_trigger " @@ -2967,7 +2936,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TEMPORARY TRIGGER index_data_upgrade_insert_trigger " "AFTER INSERT ON index_data_upgrade " "BEGIN " @@ -2993,7 +2962,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Update the |unique_index_data| table to change the column order, remove the // ON DELETE CASCADE clauses, and to apply the WITHOUT ROWID optimization. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Insert all the data. "INSERT INTO unique_index_data_upgrade " "SELECT " @@ -3008,21 +2977,21 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The trigger is no longer needed. "DROP TRIGGER unique_index_data_upgrade_insert_trigger;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The old table is no longer needed. "DROP TABLE unique_index_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Rename the table. "ALTER TABLE unique_index_data_upgrade " "RENAME TO unique_index_data;")); @@ -3032,7 +3001,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Update the |index_data| table to change the column order, remove the ON // DELETE CASCADE clauses, and to apply the WITHOUT ROWID optimization. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Insert all the data. "INSERT INTO index_data_upgrade " "SELECT " @@ -3047,21 +3016,21 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The trigger is no longer needed. "DROP TRIGGER index_data_upgrade_insert_trigger;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The old table is no longer needed. "DROP TABLE index_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Rename the table. "ALTER TABLE index_data_upgrade " "RENAME TO index_data;")); @@ -3072,7 +3041,7 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Update the |object_data| table to add the |index_data_values| column, // remove the ON DELETE CASCADE clause, and apply the WITHOUT ROWID // optimization. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Insert all the data. "INSERT INTO object_data_upgrade " "SELECT " @@ -3091,21 +3060,21 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The temporary table is no longer needed. "DROP TABLE temp_index_data_values;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // The old table is no longer needed. "DROP TABLE object_data;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( // Rename the table. "ALTER TABLE object_data_upgrade " "RENAME TO object_data;")); @@ -3116,44 +3085,42 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Update the |object_store_index| table to remove the UNIQUE constraint and // the ON DELETE CASCADE clause. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO object_store_index_upgrade " - "SELECT * " - "FROM object_store_index;")); + nsLiteralCString("INSERT INTO object_store_index_upgrade " + "SELECT * " + "FROM object_store_index;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_store_index;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_store_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE object_store_index_upgrade " - "RENAME TO object_store_index;")); + nsLiteralCString("ALTER TABLE object_store_index_upgrade " + "RENAME TO object_store_index;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Update the |object_store| table to remove the UNIQUE constraint. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO object_store_upgrade " - "SELECT * " - "FROM object_store;")); + nsLiteralCString("INSERT INTO object_store_upgrade " + "SELECT * " + "FROM object_store;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE object_store;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE object_store;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE object_store_upgrade " - "RENAME TO object_store;")); + nsLiteralCString("ALTER TABLE object_store_upgrade " + "RENAME TO object_store;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3165,9 +3132,9 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO database_upgrade " - "SELECT name, :origin, version, 0, 0, 0 " - "FROM database;"), + nsLiteralCString("INSERT INTO database_upgrade " + "SELECT name, :origin, version, 0, 0, 0 " + "FROM database;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3183,14 +3150,14 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE database;")); + rv = aConnection.ExecuteSimpleSQL("DROP TABLE database;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE database_upgrade " - "RENAME TO database;")); + nsLiteralCString("ALTER TABLE database_upgrade " + "RENAME TO database;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3200,8 +3167,8 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Make sure there's only one entry in the |database| table. nsCOMPtr stmt; MOZ_ASSERT(NS_SUCCEEDED( - aConnection.CreateStatement(NS_LITERAL_CSTRING("SELECT COUNT(*) " - "FROM database;"), + aConnection.CreateStatement(nsLiteralCString("SELECT COUNT(*) " + "FROM database;"), getter_AddRefs(stmt)))); bool hasResult; @@ -3216,17 +3183,17 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // Recreate file table triggers. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_insert_trigger " - "AFTER INSERT ON object_data " - "WHEN NEW.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(NULL, NEW.file_ids);" - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_insert_trigger " + "AFTER INSERT ON object_data " + "WHEN NEW.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(NULL, NEW.file_ids);" + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TRIGGER object_data_update_trigger " "AFTER UPDATE OF file_ids ON object_data " "WHEN OLD.file_ids IS NOT NULL OR NEW.file_ids IS NOT NULL " @@ -3238,12 +3205,12 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TRIGGER object_data_delete_trigger " - "AFTER DELETE ON object_data " - "WHEN OLD.file_ids IS NOT NULL " - "BEGIN " - "SELECT update_refcount(OLD.file_ids, NULL);" - "END;")); + nsLiteralCString("CREATE TRIGGER object_data_delete_trigger " + "AFTER DELETE ON object_data " + "WHEN OLD.file_ids IS NOT NULL " + "BEGIN " + "SELECT update_refcount(OLD.file_ids, NULL);" + "END;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3253,9 +3220,9 @@ nsresult UpgradeSchemaFrom17_0To18_0Helper::DoUpgradeInternal( // incremental auto_vacuum mode on desktop builds. rv = aConnection.ExecuteSimpleSQL( #ifdef IDB_MOBILE - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = FULL;") + "PRAGMA auto_vacuum = FULL;"_ns #else - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = INCREMENTAL;") + "PRAGMA auto_vacuum = INCREMENTAL;"_ns #endif ); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3286,34 +3253,34 @@ nsresult UpgradeSchemaFrom18_0To19_0(mozIStorageConnection& aConnection) { AUTO_PROFILER_LABEL("UpgradeSchemaFrom18_0To19_0", DOM); rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE object_store_index " - "ADD COLUMN locale TEXT;")); + nsLiteralCString("ALTER TABLE object_store_index " + "ADD COLUMN locale TEXT;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE object_store_index " - "ADD COLUMN is_auto_locale BOOLEAN;")); + nsLiteralCString("ALTER TABLE object_store_index " + "ADD COLUMN is_auto_locale BOOLEAN;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE index_data " - "ADD COLUMN value_locale BLOB;")); + nsLiteralCString("ALTER TABLE index_data " + "ADD COLUMN value_locale BLOB;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE unique_index_data " - "ADD COLUMN value_locale BLOB;")); + nsLiteralCString("ALTER TABLE unique_index_data " + "ADD COLUMN value_locale BLOB;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX index_data_value_locale_index " "ON index_data (index_id, value_locale, object_data_key, value) " "WHERE value_locale IS NOT NULL;")); @@ -3321,7 +3288,7 @@ nsresult UpgradeSchemaFrom18_0To19_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX unique_index_data_value_locale_index " "ON unique_index_data (index_id, value_locale, object_data_key, value) " "WHERE value_locale IS NOT NULL;")); @@ -3369,9 +3336,9 @@ nsresult UpgradeSchemaFrom19_0To20_0(nsIFile* aFMDirectory, nsCOMPtr stmt; nsresult rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT count(*) " - "FROM object_data " - "WHERE file_ids IS NOT NULL"), + nsLiteralCString("SELECT count(*) " + "FROM object_data " + "WHERE file_ids IS NOT NULL"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3426,21 +3393,21 @@ nsresult UpgradeSchemaFrom19_0To20_0(nsIFile* aFMDirectory, // Disable update trigger. rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER object_data_update_trigger;")); + "DROP TRIGGER object_data_update_trigger;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE object_data " - "SET file_ids = upgrade(file_ids, data) " - "WHERE file_ids IS NOT NULL;")); + nsLiteralCString("UPDATE object_data " + "SET file_ids = upgrade(file_ids, data) " + "WHERE file_ids IS NOT NULL;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Enable update trigger. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE TRIGGER object_data_update_trigger " "AFTER UPDATE OF file_ids ON object_data " "FOR EACH ROW " @@ -3627,10 +3594,10 @@ nsresult UpgradeSchemaFrom20_0To21_0(mozIStorageConnection& aConnection) { return rv; } - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "UPDATE object_data " - "SET index_data_values = upgrade_idv(index_data_values) " - "WHERE index_data_values IS NOT NULL;")); + rv = aConnection.ExecuteSimpleSQL( + nsLiteralCString("UPDATE object_data " + "SET index_data_values = upgrade_idv(index_data_values) " + "WHERE index_data_values IS NOT NULL;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3671,8 +3638,8 @@ nsresult UpgradeSchemaFrom22_0To23_0(mozIStorageConnection& aConnection, // The parameter names are not used, parameters are bound by index only // locally in the same function. nsresult rv = - aConnection.CreateStatement(NS_LITERAL_CSTRING("UPDATE database " - "SET origin = :origin;"), + aConnection.CreateStatement(nsLiteralCString("UPDATE database " + "SET origin = :origin;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3792,9 +3759,9 @@ nsresult UpgradeSchemaFrom25_0To26_0(mozIStorageConnection& aConnection) { } rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE DATABASE " - "SET origin = strip_obsolete_attributes(origin) " - "WHERE origin LIKE '%^%';")); + nsLiteralCString("UPDATE DATABASE " + "SET origin = strip_obsolete_attributes(origin) " + "WHERE origin LIKE '%^%';")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3843,9 +3810,9 @@ Result, nsresult> GetDatabaseFileURL( // only being created so it doesn't make sense to tunnel quota information to // TelemetryVFS to get corresponding QuotaObject instances for SQLite files. const nsCString directoryLockIdClause = - aDirectoryLockId >= 0 ? NS_LITERAL_CSTRING("&directoryLockId=") + - IntCString(aDirectoryLockId) - : EmptyCString(); + aDirectoryLockId >= 0 + ? "&directoryLockId="_ns + IntCString(aDirectoryLockId) + : EmptyCString(); nsAutoCString telemetryFilenameClause; if (aTelemetryId) { @@ -3856,8 +3823,8 @@ Result, nsresult> GetDatabaseFileURL( nsCOMPtr result; rv = NS_MutateURI(mutator) - .SetQuery(NS_LITERAL_CSTRING("cache=private") + - directoryLockIdClause + telemetryFilenameClause) + .SetQuery("cache=private"_ns + directoryLockIdClause + + telemetryFilenameClause) .Finalize(result); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); @@ -3960,8 +3927,8 @@ nsresult SetJournalMode(mozIStorageConnection& aConnection) { nsAutoCString pageCount; pageCount.AppendInt(kMaxWALPages); - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA wal_autocheckpoint = ") + pageCount); + rv = aConnection.ExecuteSimpleSQL("PRAGMA wal_autocheckpoint = "_ns + + pageCount); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3969,8 +3936,7 @@ nsresult SetJournalMode(mozIStorageConnection& aConnection) { } else { NS_WARNING("Failed to set WAL mode, falling back to normal journal mode."); #ifdef IDB_MOBILE - rv = aConnection.ExecuteSimpleSQL(journalModeQueryStart + - NS_LITERAL_CSTRING("truncate")); + rv = aConnection.ExecuteSimpleSQL(journalModeQueryStart + "truncate"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4156,7 +4122,7 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, return Err(rv); } - rv = connection->EnableModule(NS_LITERAL_CSTRING("filesystem")); + rv = connection->EnableModule("filesystem"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); } @@ -4199,10 +4165,10 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, #ifdef IDB_MOBILE // Turn on full auto_vacuum mode to reclaim disk space on mobile // devices (at the cost of some COMMIT speed). - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = FULL;") + "PRAGMA auto_vacuum = FULL;"_ns #else // Turn on incremental auto_vacuum mode on desktop builds. - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = INCREMENTAL;") + "PRAGMA auto_vacuum = INCREMENTAL;"_ns #endif ); if (rv == NS_ERROR_FILE_NO_DEVICE_SPACE) { @@ -4224,8 +4190,8 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, #ifdef DEBUG // Disable foreign key support while upgrading. This has to be done before // starting a transaction. - MOZ_ALWAYS_SUCCEEDS(connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA foreign_keys = OFF;"))); + MOZ_ALWAYS_SUCCEEDS( + connection->ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns)); #endif } @@ -4247,8 +4213,8 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, // The parameter names are not used, parameters are bound by index only // locally in the same function. nsresult rv = connection->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO database (name, origin) " - "VALUES (:name, :origin)"), + nsLiteralCString("INSERT INTO database (name, origin) " + "VALUES (:name, :origin)"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); @@ -4378,21 +4344,20 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, // Re-enable foreign key support after doing a foreign key check. nsCOMPtr checkStmt; MOZ_ALWAYS_SUCCEEDS(connection->CreateStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_key_check;"), - getter_AddRefs(checkStmt))); + "PRAGMA foreign_key_check;"_ns, getter_AddRefs(checkStmt))); bool hasResult; MOZ_ALWAYS_SUCCEEDS(checkStmt->ExecuteStep(&hasResult)); MOZ_ASSERT(!hasResult, "Database has inconsisistent foreign keys!"); - MOZ_ALWAYS_SUCCEEDS(connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA foreign_keys = OFF;"))); + MOZ_ALWAYS_SUCCEEDS( + connection->ExecuteSimpleSQL("PRAGMA foreign_keys = OFF;"_ns)); } #endif if (kSQLitePageSizeOverride && !newDatabase) { nsCOMPtr stmt; - rv = connection->CreateStatement(NS_LITERAL_CSTRING("PRAGMA page_size;"), + rv = connection->CreateStatement("PRAGMA page_size;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); @@ -4416,14 +4381,13 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, if (kSQLitePageSizeOverride != uint32_t(pageSize)) { // We must not be in WAL journal mode to change the page size. - rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA journal_mode = DELETE;")); + rv = connection->ExecuteSimpleSQL("PRAGMA journal_mode = DELETE;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); } - rv = connection->CreateStatement( - NS_LITERAL_CSTRING("PRAGMA journal_mode;"), getter_AddRefs(stmt)); + rv = connection->CreateStatement("PRAGMA journal_mode;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); } @@ -4461,7 +4425,7 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, } if (vacuumNeeded) { - rv = connection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM;")); + rv = connection->ExecuteSimpleSQL("VACUUM;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); } @@ -4470,8 +4434,7 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, if (newDatabase || vacuumNeeded) { if (journalModeSet) { // Make sure we checkpoint to get an accurate file size. - rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA wal_checkpoint(FULL);")); + rv = connection->ExecuteSimpleSQL("PRAGMA wal_checkpoint(FULL);"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); } @@ -4492,9 +4455,9 @@ CreateStorageConnection(nsIFile& aDBFile, nsIFile& aFMDirectory, // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = connection->CreateStatement( - NS_LITERAL_CSTRING("UPDATE database " - "SET last_vacuum_time = :time" - ", last_vacuum_size = :size;"), + nsLiteralCString("UPDATE database " + "SET last_vacuum_time = :time" + ", last_vacuum_size = :size;"), getter_AddRefs(vacuumTimeStmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return Err(rv); @@ -8302,8 +8265,7 @@ class OpenOpHelper private: void PrepareKeyConditionClauses(const nsACString& aDirectionClause, nsAutoCString aQueryStart) { - PrepareIndexKeyConditionClause(aDirectionClause, - NS_LITERAL_CSTRING("index_table."), + PrepareIndexKeyConditionClause(aDirectionClause, "index_table."_ns, std::move(aQueryStart)); } @@ -8319,7 +8281,7 @@ class OpenOpHelper private: void PrepareKeyConditionClauses(const nsACString& aDirectionClause, nsAutoCString aQueryStart) { - PrepareIndexKeyConditionClause(aDirectionClause, NS_LITERAL_CSTRING(""), + PrepareIndexKeyConditionClause(aDirectionClause, ""_ns, std::move(aQueryStart)); } @@ -9842,11 +9804,9 @@ nsAutoCString MakeColumnPairSelectionList( const nsLiteralCString& aLocaleAwareColumnName, const nsLiteralCString& aSortColumnAlias, const bool aIsLocaleAware) { return aPlainColumnName + - (aIsLocaleAware ? EmptyCString() - : NS_LITERAL_CSTRING(" as ") + aSortColumnAlias) + - NS_LITERAL_CSTRING(", ") + aLocaleAwareColumnName + - (aIsLocaleAware ? NS_LITERAL_CSTRING(" as ") + aSortColumnAlias - : EmptyCString()); + (aIsLocaleAware ? EmptyCString() : " as "_ns + aSortColumnAlias) + + ", "_ns + aLocaleAwareColumnName + + (aIsLocaleAware ? " as "_ns + aSortColumnAlias : EmptyCString()); } constexpr bool IsIncreasingOrder(const IDBCursorDirection aDirection) { @@ -9872,9 +9832,8 @@ constexpr bool IsUnique(const IDBCursorDirection aDirection) { // TODO: In principle, this could be constexpr, if operator+(nsLiteralCString, // nsLiteralCString) were constexpr and returned a literal type. nsAutoCString MakeDirectionClause(const IDBCursorDirection aDirection) { - return NS_LITERAL_CSTRING(" ORDER BY ") + kColumnNameKey + - (IsIncreasingOrder(aDirection) ? NS_LITERAL_CSTRING(" ASC") - : NS_LITERAL_CSTRING(" DESC")); + return " ORDER BY "_ns + kColumnNameKey + + (IsIncreasingOrder(aDirection) ? " ASC"_ns : " DESC"_ns); } nsresult LocalizeKey(const Key& aBaseKey, const nsCString& aLocale, @@ -9911,29 +9870,29 @@ constexpr nsLiteralCString GetComparisonOperatorString( const ComparisonOperator aComparisonOperator) { switch (aComparisonOperator) { case ComparisonOperator::LessThan: - return NS_LITERAL_CSTRING("<"); + return "<"_ns; case ComparisonOperator::LessOrEquals: - return NS_LITERAL_CSTRING("<="); + return "<="_ns; case ComparisonOperator::Equals: - return NS_LITERAL_CSTRING("=="); + return "=="_ns; case ComparisonOperator::GreaterThan: - return NS_LITERAL_CSTRING(">"); + return ">"_ns; case ComparisonOperator::GreaterOrEquals: - return NS_LITERAL_CSTRING(">="); + return ">="_ns; } // TODO: This is just to silence the "control reaches end of non-void // function" warning. Cannot use MOZ_CRASH in a constexpr function, // unfortunately. - return NS_LITERAL_CSTRING(""); + return ""_ns; } nsAutoCString GetKeyClause(const nsCString& aColumnName, const ComparisonOperator aComparisonOperator, const nsLiteralCString& aStmtParamName) { - return aColumnName + NS_LITERAL_CSTRING(" ") + - GetComparisonOperatorString(aComparisonOperator) + - NS_LITERAL_CSTRING(" :") + aStmtParamName; + return aColumnName + " "_ns + + GetComparisonOperatorString(aComparisonOperator) + " :"_ns + + aStmtParamName; } nsAutoCString GetSortKeyClause(const ComparisonOperator aComparisonOperator, @@ -10672,7 +10631,7 @@ nsresult DatabaseConnection::Init() { MOZ_ASSERT(!mInWriteTransaction); CachedStatement stmt; - nsresult rv = GetCachedStatement(NS_LITERAL_CSTRING("BEGIN;"), &stmt); + nsresult rv = GetCachedStatement("BEGIN;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10706,10 +10665,9 @@ nsresult DatabaseConnection::GetCachedStatement( nsCString msg; MOZ_ALWAYS_SUCCEEDS((*mStorageConnection)->GetLastErrorString(msg)); - nsAutoCString error = - NS_LITERAL_CSTRING("The statement '") + aQuery + - NS_LITERAL_CSTRING("' failed to compile with the error message '") + - msg + NS_LITERAL_CSTRING("'."); + nsAutoCString error = "The statement '"_ns + aQuery + + "' failed to compile with the error message '"_ns + + msg + "'."_ns; NS_WARNING(error.get()); #endif @@ -10758,7 +10716,7 @@ nsresult DatabaseConnection::BeginWriteTransaction() { AUTO_PROFILER_LABEL("DatabaseConnection::BeginWriteTransaction", DOM); // Release our read locks. - nsresult rv = ExecuteCachedStatement(NS_LITERAL_CSTRING("ROLLBACK;")); + nsresult rv = ExecuteCachedStatement("ROLLBACK;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10772,7 +10730,7 @@ nsresult DatabaseConnection::BeginWriteTransaction() { new UpdateRefcountFunction(this, **mFileManager); rv = (*mStorageConnection) - ->CreateFunction(NS_LITERAL_CSTRING("update_refcount"), + ->CreateFunction("update_refcount"_ns, /* aNumArguments */ 2, function); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -10786,7 +10744,7 @@ nsresult DatabaseConnection::BeginWriteTransaction() { // NS_ERROR_STORAGE_BUSY, we could actually use ExecuteCachedStatement and // simplify this. CachedStatement beginStmt; - rv = GetCachedStatement(NS_LITERAL_CSTRING("BEGIN IMMEDIATE;"), &beginStmt); + rv = GetCachedStatement("BEGIN IMMEDIATE;"_ns, &beginStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10829,7 +10787,7 @@ nsresult DatabaseConnection::CommitWriteTransaction() { AUTO_PROFILER_LABEL("DatabaseConnection::CommitWriteTransaction", DOM); - const nsresult rv = ExecuteCachedStatement(NS_LITERAL_CSTRING("COMMIT;")); + const nsresult rv = ExecuteCachedStatement("COMMIT;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10850,7 +10808,7 @@ void DatabaseConnection::RollbackWriteTransaction() { } CachedStatement stmt; - nsresult rv = GetCachedStatement(NS_LITERAL_CSTRING("ROLLBACK;"), &stmt); + nsresult rv = GetCachedStatement("ROLLBACK;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -10874,7 +10832,7 @@ void DatabaseConnection::FinishWriteTransaction() { mUpdateRefcountFunction->Reset(); } - const nsresult rv = ExecuteCachedStatement(NS_LITERAL_CSTRING("BEGIN;")); + const nsresult rv = ExecuteCachedStatement("BEGIN;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -10891,7 +10849,7 @@ nsresult DatabaseConnection::StartSavepoint() { AUTO_PROFILER_LABEL("DatabaseConnection::StartSavepoint", DOM); const nsresult rv = - ExecuteCachedStatement(NS_LITERAL_CSTRING(SAVEPOINT_CLAUSE)); + ExecuteCachedStatement(nsLiteralCString(SAVEPOINT_CLAUSE)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10915,7 +10873,7 @@ nsresult DatabaseConnection::ReleaseSavepoint() { AUTO_PROFILER_LABEL("DatabaseConnection::ReleaseSavepoint", DOM); nsresult rv = - ExecuteCachedStatement(NS_LITERAL_CSTRING("RELEASE " SAVEPOINT_CLAUSE)); + ExecuteCachedStatement(nsLiteralCString("RELEASE " SAVEPOINT_CLAUSE)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -10947,7 +10905,7 @@ nsresult DatabaseConnection::RollbackSavepoint() { CachedStatement stmt; nsresult rv = GetCachedStatement( - NS_LITERAL_CSTRING("ROLLBACK TO " SAVEPOINT_CLAUSE), &stmt); + nsLiteralCString("ROLLBACK TO " SAVEPOINT_CLAUSE), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -11018,12 +10976,12 @@ void DatabaseConnection::DoIdleProcessing(bool aNeedsCheckpoint) { CachedStatement rollbackStmt; CachedStatement beginStmt; if (aNeedsCheckpoint || freelistCount) { - rv = GetCachedStatement(NS_LITERAL_CSTRING("ROLLBACK;"), &rollbackStmt); + rv = GetCachedStatement("ROLLBACK;"_ns, &rollbackStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return; } - rv = GetCachedStatement(NS_LITERAL_CSTRING("BEGIN;"), &beginStmt); + rv = GetCachedStatement("BEGIN;"_ns, &beginStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -11103,14 +11061,13 @@ nsresult DatabaseConnection::ReclaimFreePagesWhileIdle( } CachedStatement beginImmediateStmt; - rv = GetCachedStatement(NS_LITERAL_CSTRING("BEGIN IMMEDIATE;"), - &beginImmediateStmt); + rv = GetCachedStatement("BEGIN IMMEDIATE;"_ns, &beginImmediateStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } CachedStatement commitStmt; - rv = GetCachedStatement(NS_LITERAL_CSTRING("COMMIT;"), &commitStmt); + rv = GetCachedStatement("COMMIT;"_ns, &commitStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -11192,8 +11149,7 @@ nsresult DatabaseConnection::GetFreelistCount(CachedStatement& aCachedStatement, nsresult rv; if (!aCachedStatement) { - rv = GetCachedStatement(NS_LITERAL_CSTRING("PRAGMA freelist_count;"), - &aCachedStatement); + rv = GetCachedStatement("PRAGMA freelist_count;"_ns, &aCachedStatement); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -11233,8 +11189,7 @@ void DatabaseConnection::Close() { if (mUpdateRefcountFunction) { MOZ_ALWAYS_SUCCEEDS( - (*mStorageConnection) - ->RemoveFunction(NS_LITERAL_CSTRING("update_refcount"))); + (*mStorageConnection)->RemoveFunction("update_refcount"_ns)); mUpdateRefcountFunction = nullptr; } @@ -11801,9 +11756,9 @@ nsresult DatabaseConnection::UpdateRefcountFunction::DatabaseUpdateFunction:: // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = connection->GetCachedStatement( - NS_LITERAL_CSTRING("UPDATE file " - "SET refcount = refcount + :delta " - "WHERE id = :id"), + nsLiteralCString("UPDATE file " + "SET refcount = refcount + :delta " + "WHERE id = :id"), &mUpdateStatement); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -11837,9 +11792,9 @@ nsresult DatabaseConnection::UpdateRefcountFunction::DatabaseUpdateFunction:: if (!mSelectStatement) { // The parameter names are not used, parameters are bound by index only // locally in the same function. - rv = connection->GetCachedStatement(NS_LITERAL_CSTRING("SELECT id " - "FROM file " - "WHERE id = :id"), + rv = connection->GetCachedStatement(nsLiteralCString("SELECT id " + "FROM file " + "WHERE id = :id"), &mSelectStatement); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -11872,8 +11827,8 @@ nsresult DatabaseConnection::UpdateRefcountFunction::DatabaseUpdateFunction:: // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = connection->GetCachedStatement( - NS_LITERAL_CSTRING("INSERT INTO file (id, refcount) " - "VALUES(:id, :delta)"), + nsLiteralCString("INSERT INTO file (id, refcount) " + "VALUES(:id, :delta)"), &mInsertStatement); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -12419,8 +12374,7 @@ bool ConnectionPool::ScheduleTransaction(TransactionInfo& aTransactionInfo, nsresult rv = NS_NewNamedThread(runnable->GetThreadName(), getter_AddRefs(newThread), runnable); if (NS_SUCCEEDED(rv)) { - newThread->SetNameForWakeupTelemetry( - NS_LITERAL_CSTRING("IndexedDB (all)")); + newThread->SetNameForWakeupTelemetry("IndexedDB (all)"_ns); MOZ_ASSERT(newThread); IDB_DEBUG_LOG(("ConnectionPool created thread %" PRIu32, @@ -16442,8 +16396,8 @@ nsresult FileManager::Init(nsIFile* aDirectory, } nsCOMPtr stmt; - rv = aConnection.CreateStatement(NS_LITERAL_CSTRING("SELECT id, refcount " - "FROM file"), + rv = aConnection.CreateStatement(nsLiteralCString("SELECT id, refcount " + "FROM file"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -16685,7 +16639,7 @@ nsresult FileManager::InitDirectory(nsIFile& aDirectory, nsIFile& aDatabaseFile, mozStorageTransaction transaction(connection.get(), false); rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE VIRTUAL TABLE fs USING filesystem;")); + "CREATE VIRTUAL TABLE fs USING filesystem;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -16694,9 +16648,9 @@ nsresult FileManager::InitDirectory(nsIFile& aDirectory, nsIFile& aDatabaseFile, // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = connection->CreateStatement( - NS_LITERAL_CSTRING("SELECT name, (name IN (SELECT id FROM file)) " - "FROM fs " - "WHERE path = :path"), + nsLiteralCString("SELECT name, (name IN (SELECT id FROM file)) " + "FROM fs " + "WHERE path = :path"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -16765,7 +16719,7 @@ nsresult FileManager::InitDirectory(nsIFile& aDirectory, nsIFile& aDatabaseFile, return rv; } - rv = connection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TABLE fs;")); + rv = connection->ExecuteSimpleSQL("DROP TABLE fs;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -16983,8 +16937,7 @@ nsThreadPool* QuotaClient::GetOrCreateThreadPool() { // Don't keep idle threads alive very long. MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadTimeout(5 * PR_MSEC_PER_SEC)); - MOZ_ALWAYS_SUCCEEDS( - threadPool->SetName(NS_LITERAL_CSTRING("IndexedDB Mnt"))); + MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("IndexedDB Mnt"_ns)); mMaintenanceThreadPool = std::move(threadPool); } @@ -17031,7 +16984,7 @@ nsresult QuotaClient::UpgradeStorageFrom1_0To2_0(nsIFile* aDirectory) { // to check that possibility here too. // We do this on all platforms, because the origin directory may have // been created on Windows and now accessed on different OS. - nsString subdirNameWithDot = subdirName + NS_LITERAL_STRING("."); + nsString subdirNameWithDot = subdirName + u"."_ns; if (NS_WARN_IF(!databaseFilenames.GetEntry(subdirNameWithDot))) { continue; } @@ -17119,7 +17072,7 @@ nsresult QuotaClient::UpgradeStorageFrom2_1To2_2(nsIFile* aDirectory) { // It's reported that files ending with ".tmp" somehow live in the indexedDB // directories in Bug 1503883. Such files shouldn't exist in the indexedDB // directory so remove them in this upgrade. - if (StringEndsWith(leafName, NS_LITERAL_STRING(".tmp"))) { + if (StringEndsWith(leafName, u".tmp"_ns)) { IDB_WARNING("Deleting unknown temporary file!"); rv = file->Remove(false); @@ -18587,8 +18540,8 @@ nsresult DatabaseMaintenance::CheckIntegrity(mozIStorageConnection& aConnection, // later operations require zero live statements. { nsCOMPtr stmt; - rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("PRAGMA integrity_check(1);"), getter_AddRefs(stmt)); + rv = aConnection.CreateStatement("PRAGMA integrity_check(1);"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -18618,8 +18571,8 @@ nsresult DatabaseMaintenance::CheckIntegrity(mozIStorageConnection& aConnection, int32_t foreignKeysWereEnabled; { nsCOMPtr stmt; - rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_keys;"), getter_AddRefs(stmt)); + rv = aConnection.CreateStatement("PRAGMA foreign_keys;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -18639,8 +18592,7 @@ nsresult DatabaseMaintenance::CheckIntegrity(mozIStorageConnection& aConnection, } if (!foreignKeysWereEnabled) { - rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA foreign_keys = ON;")); + rv = aConnection.ExecuteSimpleSQL("PRAGMA foreign_keys = ON;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -18649,9 +18601,8 @@ nsresult DatabaseMaintenance::CheckIntegrity(mozIStorageConnection& aConnection, bool foreignKeyError; { nsCOMPtr stmt; - rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_key_check;"), - getter_AddRefs(stmt)); + rv = aConnection.CreateStatement("PRAGMA foreign_key_check;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -18719,8 +18670,8 @@ nsresult DatabaseMaintenance::DetermineMaintenanceAction( // Check to see when we last vacuumed this database. nsCOMPtr stmt; rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT last_vacuum_time, last_vacuum_size " - "FROM database;"), + nsLiteralCString("SELECT last_vacuum_time, last_vacuum_size " + "FROM database;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -18768,7 +18719,7 @@ nsresult DatabaseMaintenance::DetermineMaintenanceAction( // Create a temporary copy of the dbstat table to speed up the queries that // come later. - rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection.ExecuteSimpleSQL(nsLiteralCString( "CREATE VIRTUAL TABLE __stats__ USING dbstat;" "CREATE TEMP TABLE __temp_stats__ AS SELECT * FROM __stats__;")); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -18778,7 +18729,7 @@ nsresult DatabaseMaintenance::DetermineMaintenanceAction( // Calculate the percentage of the database pages that are not in contiguous // order. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT SUM(__ts1__.pageno != __ts2__.pageno + 1) * 100.0 / COUNT(*) " "FROM __temp_stats__ AS __ts1__, __temp_stats__ AS __ts2__ " "WHERE __ts1__.name = __ts2__.name " @@ -18824,7 +18775,7 @@ nsresult DatabaseMaintenance::DetermineMaintenanceAction( } // See if there are any free pages that we can reclaim. - rv = aConnection.CreateStatement(NS_LITERAL_CSTRING("PRAGMA freelist_count;"), + rv = aConnection.CreateStatement("PRAGMA freelist_count;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -18854,8 +18805,8 @@ nsresult DatabaseMaintenance::DetermineMaintenanceAction( // Calculate the percentage of unused bytes on pages in the database. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT SUM(unused) * 100.0 / SUM(pgsize) " - "FROM __temp_stats__;"), + nsLiteralCString("SELECT SUM(unused) * 100.0 / SUM(pgsize) " + "FROM __temp_stats__;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -18893,8 +18844,7 @@ void DatabaseMaintenance::IncrementalVacuum( return; } - nsresult rv = aConnection.ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA incremental_vacuum;")); + nsresult rv = aConnection.ExecuteSimpleSQL("PRAGMA incremental_vacuum;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -18911,7 +18861,7 @@ void DatabaseMaintenance::FullVacuum(mozIStorageConnection& aConnection, return; } - nsresult rv = aConnection.ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM;")); + nsresult rv = aConnection.ExecuteSimpleSQL("VACUUM;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -18931,9 +18881,9 @@ void DatabaseMaintenance::FullVacuum(mozIStorageConnection& aConnection, // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("UPDATE database " - "SET last_vacuum_time = :time" - ", last_vacuum_size = :size;"), + nsLiteralCString("UPDATE database " + "SET last_vacuum_time = :time" + ", last_vacuum_size = :size;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return; @@ -19150,8 +19100,8 @@ nsAutoCString DatabaseOperationBase::GetBindingClauseForKeyRange( nsAutoCString result; if (aKeyRange.isOnly()) { // Both keys equal. - result = andStr + aKeyColumnName + NS_LITERAL_CSTRING(" =") + spacecolon + - kStmtParamNameLowerKey; + result = + andStr + aKeyColumnName + " ="_ns + spacecolon + kStmtParamNameLowerKey; } else { if (!aKeyRange.lower().IsUnset()) { // Lower key is set. @@ -19453,8 +19403,7 @@ nsresult DatabaseOperationBase::BindKeyRangeToStatement( void CommonOpenOpHelperBase::AppendConditionClause( const nsACString& aColumnName, const nsACString& aStatementParameterName, bool aLessThan, bool aEquals, nsCString& aResult) { - aResult += - NS_LITERAL_CSTRING(" AND ") + aColumnName + NS_LITERAL_CSTRING(" "); + aResult += " AND "_ns + aColumnName + " "_ns; if (aLessThan) { aResult.Append('<'); @@ -19466,7 +19415,7 @@ void CommonOpenOpHelperBase::AppendConditionClause( aResult.Append('='); } - aResult += NS_LITERAL_CSTRING(" :") + aStatementParameterName; + aResult += " :"_ns + aStatementParameterName; } // static @@ -19535,30 +19484,28 @@ nsresult DatabaseOperationBase::InsertIndexTableRows( stmt.Reset(); } else if (info.mUnique) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("INSERT INTO unique_index_data " - "(index_id, value, object_store_id, " - "object_data_key, value_locale) " - "VALUES (:") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(", :") + - kStmtParamNameValue + NS_LITERAL_CSTRING(", :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(", :") + - kStmtParamNameObjectDataKey + NS_LITERAL_CSTRING(", :") + - kStmtParamNameValueLocale + NS_LITERAL_CSTRING(");"), + nsLiteralCString("INSERT INTO unique_index_data " + "(index_id, value, object_store_id, " + "object_data_key, value_locale) " + "VALUES (:") + + kStmtParamNameIndexId + ", :"_ns + kStmtParamNameValue + + ", :"_ns + kStmtParamNameObjectStoreId + ", :"_ns + + kStmtParamNameObjectDataKey + ", :"_ns + + kStmtParamNameValueLocale + ");"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("INSERT OR IGNORE INTO index_data " - "(index_id, value, object_data_key, " - "object_store_id, value_locale) " - "VALUES (:") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(", :") + - kStmtParamNameValue + NS_LITERAL_CSTRING(", :") + - kStmtParamNameObjectDataKey + NS_LITERAL_CSTRING(", :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(", :") + - kStmtParamNameValueLocale + NS_LITERAL_CSTRING(");"), + nsLiteralCString("INSERT OR IGNORE INTO index_data " + "(index_id, value, object_data_key, " + "object_store_id, value_locale) " + "VALUES (:") + + kStmtParamNameIndexId + ", :"_ns + kStmtParamNameValue + + ", :"_ns + kStmtParamNameObjectDataKey + ", :"_ns + + kStmtParamNameObjectStoreId + ", :"_ns + + kStmtParamNameValueLocale + ");"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -19646,22 +19593,21 @@ nsresult DatabaseOperationBase::DeleteIndexDataTableRows( stmt.Reset(); } else if (indexValue.mUnique) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM unique_index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(" AND value = :") + - kStmtParamNameValue + NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM unique_index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " AND value = :"_ns + + kStmtParamNameValue + ";"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(" AND value = :") + - kStmtParamNameValue + - NS_LITERAL_CSTRING(" AND object_data_key = :") + - kStmtParamNameObjectDataKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " AND value = :"_ns + + kStmtParamNameValue + " AND object_data_key = :"_ns + + kStmtParamNameObjectDataKey + ";"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -19723,11 +19669,11 @@ nsresult DatabaseOperationBase::DeleteObjectStoreDataTableRowsWithIndexes( if (singleRowOnly) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT index_data_values " - "FROM object_data " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(" AND key = :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("SELECT index_data_values " + "FROM object_data " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + " AND key = :"_ns + + kStmtParamNameKey + ";"_ns, &selectStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -19744,12 +19690,11 @@ nsresult DatabaseOperationBase::DeleteObjectStoreDataTableRowsWithIndexes( MaybeGetBindingClauseForKeyRange(aKeyRange, kColumnNameKey); rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT index_data_values, ") + kColumnNameKey + - NS_LITERAL_CSTRING(" " - "FROM object_data " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + keyRangeClause + - NS_LITERAL_CSTRING(";"), + "SELECT index_data_values, "_ns + kColumnNameKey + + nsLiteralCString(" " + "FROM object_data " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + keyRangeClause + ";"_ns, &selectStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -19798,10 +19743,10 @@ nsresult DatabaseOperationBase::DeleteObjectStoreDataTableRowsWithIndexes( MOZ_ALWAYS_SUCCEEDS(deleteStmt->Reset()); } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_data " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(" AND key = :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM object_data " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + " AND key = :"_ns + + kStmtParamNameKey + ";"_ns, &deleteStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -19857,12 +19802,11 @@ nsresult DatabaseOperationBase::UpdateIndexValues( DatabaseConnection::CachedStatement updateStmt; rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_data " - "SET index_data_values = :") + - kStmtParamNameIndexDataValues + - NS_LITERAL_CSTRING(" WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(" AND key = :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("UPDATE object_data " + "SET index_data_values = :") + + kStmtParamNameIndexDataValues + " WHERE object_store_id = :"_ns + + kStmtParamNameObjectStoreId + " AND key = :"_ns + kStmtParamNameKey + + ";"_ns, [&indexDataValues, indexDataValuesLength, aObjectStoreId, &aObjectStoreKey](mozIStorageStatement& updateStmt) { nsresult rv = @@ -19907,10 +19851,10 @@ nsresult DatabaseOperationBase::ObjectStoreHasIndexes( DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT id " - "FROM object_store_index " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + kOpenLimit + NS_LITERAL_CSTRING("1;"), + nsLiteralCString("SELECT id " + "FROM object_store_index " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + kOpenLimit + "1;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -21244,8 +21188,8 @@ nsresult OpenDatabaseOp::LoadDatabaseInformation( // Load version information. nsCOMPtr stmt; nsresult rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT name, origin, version " - "FROM database"), + nsLiteralCString("SELECT name, origin, version " + "FROM database"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -21294,8 +21238,8 @@ nsresult OpenDatabaseOp::LoadDatabaseInformation( // Load object store names and ids. rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING("SELECT id, auto_increment, name, key_path " - "FROM object_store"), + nsLiteralCString("SELECT id, auto_increment, name, key_path " + "FROM object_store"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -21399,7 +21343,7 @@ nsresult OpenDatabaseOp::LoadDatabaseInformation( // Load index information rv = aConnection.CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT " "id, object_store_id, name, key_path, unique_index, multientry, " "locale, is_auto_locale " @@ -21575,9 +21519,8 @@ nsresult OpenDatabaseOp::UpdateLocaleAwareIndex( // The parameter names are not used, parameters are bound by index only // locally in the same function. - nsCString readQuery = - NS_LITERAL_CSTRING("SELECT value, object_data_key FROM ") + indexTable + - NS_LITERAL_CSTRING(" WHERE index_id = :index_id"); + nsCString readQuery = "SELECT value, object_data_key FROM "_ns + indexTable + + " WHERE index_id = :index_id"_ns; nsCOMPtr readStmt; rv = aConnection.CreateStatement(readQuery, getter_AddRefs(readStmt)); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -21596,13 +21539,10 @@ nsresult OpenDatabaseOp::UpdateLocaleAwareIndex( if (needCreateWriteQuery) { needCreateWriteQuery = false; nsCString writeQuery = - NS_LITERAL_CSTRING("UPDATE ") + indexTable + - NS_LITERAL_CSTRING("SET value_locale = :") + - kStmtParamNameValueLocale + - NS_LITERAL_CSTRING(" WHERE index_id = :") + kStmtParamNameIndexId + - NS_LITERAL_CSTRING(" AND value = :") + kStmtParamNameValue + - NS_LITERAL_CSTRING(" AND object_data_key = :") + - kStmtParamNameObjectDataKey; + "UPDATE "_ns + indexTable + "SET value_locale = :"_ns + + kStmtParamNameValueLocale + " WHERE index_id = :"_ns + + kStmtParamNameIndexId + " AND value = :"_ns + kStmtParamNameValue + + " AND object_data_key = :"_ns + kStmtParamNameObjectDataKey; rv = aConnection.CreateStatement(writeQuery, getter_AddRefs(writeStmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -21658,7 +21598,7 @@ nsresult OpenDatabaseOp::UpdateLocaleAwareIndex( // The parameter names are not used, parameters are bound by index only // locally in the same function. - nsCString metaQuery = NS_LITERAL_CSTRING( + nsCString metaQuery = nsLiteralCString( "UPDATE object_store_index SET " "locale = :locale WHERE id = :id"); nsCOMPtr metaStmt; @@ -22189,8 +22129,8 @@ nsresult OpenDatabaseOp::VersionChangeOp::DoDatabaseWork( // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("UPDATE database " - "SET version = :version;"), + nsLiteralCString("UPDATE database " + "SET version = :version;"), [this](mozIStorageStatement& updateStmt) { nsresult rv = updateStmt.BindInt64ByIndex(0, int64_t(mRequestedVersion)); @@ -22285,8 +22225,8 @@ void DeleteDatabaseOp::LoadPreviousVersion(nsIFile& aDatabaseFile) { #ifdef DEBUG { nsCOMPtr stmt; - rv = connection->CreateStatement(NS_LITERAL_CSTRING("SELECT name " - "FROM database"), + rv = connection->CreateStatement(nsLiteralCString("SELECT name " + "FROM database"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return; @@ -22309,8 +22249,8 @@ void DeleteDatabaseOp::LoadPreviousVersion(nsIFile& aDatabaseFile) { #endif nsCOMPtr stmt; - rv = connection->CreateStatement(NS_LITERAL_CSTRING("SELECT version " - "FROM database"), + rv = connection->CreateStatement(nsLiteralCString("SELECT version " + "FROM database"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return; @@ -22993,9 +22933,9 @@ nsresult TransactionBase::CommitOp::WriteAutoIncrementCounts() { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = connection->GetCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_store " - "SET auto_increment = :auto_increment WHERE id " - "= :object_store_id;"), + nsLiteralCString("UPDATE object_store " + "SET auto_increment = :auto_increment WHERE id " + "= :object_store_id;"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -23056,8 +22996,8 @@ void TransactionBase::CommitOp::AssertForeignKeyConsistency( MOZ_ASSERT(mTransaction->GetMode() != IDBTransaction::Mode::ReadOnly); DatabaseConnection::CachedStatement pragmaStmt; - MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_keys;"), &pragmaStmt)); + MOZ_ALWAYS_SUCCEEDS( + aConnection->GetCachedStatement("PRAGMA foreign_keys;"_ns, &pragmaStmt)); bool hasResult; MOZ_ALWAYS_SUCCEEDS(pragmaStmt->ExecuteStep(&hasResult)); @@ -23071,7 +23011,7 @@ void TransactionBase::CommitOp::AssertForeignKeyConsistency( DatabaseConnection::CachedStatement checkStmt; MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("PRAGMA foreign_key_check;"), &checkStmt)); + "PRAGMA foreign_key_check;"_ns, &checkStmt)); MOZ_ALWAYS_SUCCEEDS(checkStmt->ExecuteStep(&hasResult)); @@ -23455,11 +23395,11 @@ nsresult CreateObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { DatabaseConnection::CachedStatement stmt; // The parameter names are not used, parameters are bound by index only // locally in the same function. - MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT name " - "FROM object_store " - "WHERE name = :name;"), - &stmt)); + MOZ_ALWAYS_SUCCEEDS( + aConnection->GetCachedStatement(nsLiteralCString("SELECT name " + "FROM object_store " + "WHERE name = :name;"), + &stmt)); MOZ_ALWAYS_SUCCEEDS(stmt->BindStringByIndex(0, mMetadata.name())); @@ -23483,7 +23423,7 @@ nsresult CreateObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT INTO object_store (id, auto_increment, name, key_path) " "VALUES (:id, :auto_increment, :name, :key_path);"), [this](mozIStorageStatement& stmt) { @@ -23548,10 +23488,10 @@ nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { { // Make sure |mIsLastObjectStore| is telling the truth. DatabaseConnection::CachedStatement stmt; - MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT id " - "FROM object_store;"), - &stmt)); + MOZ_ALWAYS_SUCCEEDS( + aConnection->GetCachedStatement(nsLiteralCString("SELECT id " + "FROM object_store;"), + &stmt)); bool foundThisObjectStore = false; bool foundOtherObjectStore = false; @@ -23594,32 +23534,29 @@ nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { if (mIsLastObjectStore) { // We can just delete everything if this is the last object store. - rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM index_data;")); + rv = aConnection->ExecuteCachedStatement("DELETE FROM index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM unique_index_data;")); + "DELETE FROM unique_index_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_data;")); + rv = aConnection->ExecuteCachedStatement("DELETE FROM object_data;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_store_index;")); + "DELETE FROM object_store_index;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_store;")); + rv = aConnection->ExecuteCachedStatement("DELETE FROM object_store;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -23642,8 +23579,8 @@ nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_store_index " - "WHERE object_store_id = :object_store_id;"), + nsLiteralCString("DELETE FROM object_store_index " + "WHERE object_store_id = :object_store_id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindInt64ByIndex(0, mMetadata->mCommonMetadata.id()); @@ -23662,8 +23599,8 @@ nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_data " - "WHERE object_store_id = :object_store_id;"), + nsLiteralCString("DELETE FROM object_data " + "WHERE object_store_id = :object_store_id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindInt64ByIndex(0, mMetadata->mCommonMetadata.id()); @@ -23681,8 +23618,8 @@ nsresult DeleteObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_store " - "WHERE id = :object_store_id;"), + nsLiteralCString("DELETE FROM object_store " + "WHERE id = :object_store_id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindInt64ByIndex(0, mMetadata->mCommonMetadata.id()); @@ -23734,9 +23671,9 @@ nsresult RenameObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT name " - "FROM object_store " - "WHERE name = :name AND id != :id;"), + nsLiteralCString("SELECT name " + "FROM object_store " + "WHERE name = :name AND id != :id;"), &stmt)); MOZ_ALWAYS_SUCCEEDS(stmt->BindStringByIndex(0, mNewName)); @@ -23763,9 +23700,9 @@ nsresult RenameObjectStoreOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_store " - "SET name = :name " - "WHERE id = :id;"), + nsLiteralCString("UPDATE object_store " + "SET name = :name " + "WHERE id = :id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindStringByIndex(0, mNewName); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -23848,10 +23785,10 @@ nsresult CreateIndexOp::InsertDataFromObjectStoreInternal( // The parameter names are not used, parameters are bound by index only // locally in the same function. const nsresult rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_data " - "SET index_data_values = update_index_data_values " - "(key, index_data_values, file_ids, data) " - "WHERE object_store_id = :object_store_id;"), + nsLiteralCString("UPDATE object_data " + "SET index_data_values = update_index_data_values " + "(key, index_data_values, file_ids, data) " + "WHERE object_store_id = :object_store_id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindInt64ByIndex(0, mObjectStoreId); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -23918,7 +23855,7 @@ nsresult CreateIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT name " "FROM object_store_index " "WHERE object_store_id = :object_store_id AND name = :name;"), @@ -23947,7 +23884,7 @@ nsresult CreateIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT INTO object_store_index (id, name, key_path, unique_index, " "multientry, object_store_id, locale, " "is_auto_locale) " @@ -24253,11 +24190,11 @@ nsresult DeleteIndexOp::RemoveReferencesToIndex( // column if this is the last index. Simply set it to NULL. DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_data " - "SET index_data_values = NULL " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(" AND key = :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("UPDATE object_data " + "SET index_data_values = NULL " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + " AND key = :"_ns + + kStmtParamNameKey + ";"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -24348,9 +24285,9 @@ nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT id " - "FROM object_store_index " - "WHERE object_store_id = :object_store_id;"), + nsLiteralCString("SELECT id " + "FROM object_store_index " + "WHERE object_store_id = :object_store_id;"), &stmt)); MOZ_ALWAYS_SUCCEEDS(stmt->BindInt64ByIndex(0, mObjectStoreId)); @@ -24402,16 +24339,15 @@ nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { if (mUnique) { if (mIsLastIndex) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("/* do not warn (bug someone else) */ " - "SELECT value, object_data_key " - "FROM unique_index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + - NS_LITERAL_CSTRING(" ORDER BY object_data_key ASC;"), + nsLiteralCString("/* do not warn (bug someone else) */ " + "SELECT value, object_data_key " + "FROM unique_index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " ORDER BY object_data_key ASC;"_ns, &selectStmt); } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "/* do not warn (bug out) */ " "SELECT unique_index_data.value, " "unique_index_data.object_data_key, " @@ -24421,38 +24357,36 @@ nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { "ON unique_index_data.object_data_key = object_data.key " "WHERE unique_index_data.index_id = :") + kStmtParamNameIndexId + - NS_LITERAL_CSTRING(" AND object_data.object_store_id = :") + + " AND object_data.object_store_id = :"_ns + kStmtParamNameObjectStoreId + - NS_LITERAL_CSTRING( + nsLiteralCString( " ORDER BY unique_index_data.object_data_key ASC;"), &selectStmt); } } else { if (mIsLastIndex) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("/* do not warn (bug me not) */ " - "SELECT value, object_data_key " - "FROM index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + - NS_LITERAL_CSTRING(" AND object_store_id = :") + - kStmtParamNameObjectStoreId + - NS_LITERAL_CSTRING(" ORDER BY object_data_key ASC;"), + nsLiteralCString("/* do not warn (bug me not) */ " + "SELECT value, object_data_key " + "FROM index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " AND object_store_id = :"_ns + + kStmtParamNameObjectStoreId + " ORDER BY object_data_key ASC;"_ns, &selectStmt); } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("/* do not warn (bug off) */ " - "SELECT index_data.value, " - "index_data.object_data_key, " - "object_data.index_data_values " - "FROM index_data " - "JOIN object_data " - "ON index_data.object_data_key = object_data.key " - "WHERE index_data.index_id = :") + + nsLiteralCString("/* do not warn (bug off) */ " + "SELECT index_data.value, " + "index_data.object_data_key, " + "object_data.index_data_values " + "FROM index_data " + "JOIN object_data " + "ON index_data.object_data_key = object_data.key " + "WHERE index_data.index_id = :") + kStmtParamNameIndexId + - NS_LITERAL_CSTRING(" AND object_data.object_store_id = :") + + " AND object_data.object_store_id = :"_ns + kStmtParamNameObjectStoreId + - NS_LITERAL_CSTRING(" ORDER BY index_data.object_data_key ASC;"), + " ORDER BY index_data.object_data_key ASC;"_ns, &selectStmt); } } @@ -24547,19 +24481,18 @@ nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { } else { if (mUnique) { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM unique_index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(" AND value = :") + - kStmtParamNameValue + NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM unique_index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " AND value = :"_ns + + kStmtParamNameValue + ";"_ns, &deleteIndexRowStmt); } else { rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM index_data " - "WHERE index_id = :") + - kStmtParamNameIndexId + NS_LITERAL_CSTRING(" AND value = :") + - kStmtParamNameValue + - NS_LITERAL_CSTRING(" AND object_data_key = :") + - kStmtParamNameObjectDataKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM index_data " + "WHERE index_id = :") + + kStmtParamNameIndexId + " AND value = :"_ns + + kStmtParamNameValue + " AND object_data_key = :"_ns + + kStmtParamNameObjectDataKey + ";"_ns, &deleteIndexRowStmt); } if (NS_WARN_IF(NS_FAILED(rv))) { @@ -24606,8 +24539,8 @@ nsresult DeleteIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { } rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_store_index " - "WHERE id = :index_id;"), + nsLiteralCString("DELETE FROM object_store_index " + "WHERE id = :index_id;"), [this](mozIStorageStatement& deleteStmt) { nsresult rv = deleteStmt.BindInt64ByIndex(0, mIndexId); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -24652,11 +24585,11 @@ nsresult RenameIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. MOZ_ALWAYS_SUCCEEDS(aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT name " - "FROM object_store_index " - "WHERE object_store_id = :object_store_id " - "AND name = :name " - "AND id != :id;"), + nsLiteralCString("SELECT name " + "FROM object_store_index " + "WHERE object_store_id = :object_store_id " + "AND name = :name " + "AND id != :id;"), &stmt)); MOZ_ALWAYS_SUCCEEDS(stmt->BindInt64ByIndex(0, mObjectStoreId)); @@ -24687,9 +24620,9 @@ nsresult RenameIndexOp::DoDatabaseWork(DatabaseConnection* aConnection) { // The parameter names are not used, parameters are bound by index only // locally in the same function. rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("UPDATE object_store_index " - "SET name = :name " - "WHERE id = :id;"), + nsLiteralCString("UPDATE object_store_index " + "SET name = :name " + "WHERE id = :id;"), [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindStringByIndex(0, mNewName); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -24936,11 +24869,11 @@ nsresult ObjectStoreAddOrPutRequestOp::RemoveOldIndexDataValues( DatabaseConnection::CachedStatement indexValuesStmt; nsresult rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT index_data_values " - "FROM object_data " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(" AND key = :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(";"), + nsLiteralCString("SELECT index_data_values " + "FROM object_data " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + " AND key = :"_ns + kStmtParamNameKey + + ";"_ns, &indexValuesStmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -25117,18 +25050,16 @@ nsresult ObjectStoreAddOrPutRequestOp::DoDatabaseWork( // if we allow overwrite or not. By not allowing overwrite we raise // detectable errors rather than corrupting data. DatabaseConnection::CachedStatement stmt; - const auto optReplaceDirective = (!mOverwrite || keyUnset) - ? NS_LITERAL_CSTRING("") - : NS_LITERAL_CSTRING("OR REPLACE "); + const auto optReplaceDirective = + (!mOverwrite || keyUnset) ? ""_ns : "OR REPLACE "_ns; rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("INSERT ") + optReplaceDirective + - NS_LITERAL_CSTRING("INTO object_data " - "(object_store_id, key, file_ids, data) " - "VALUES (:") + - kStmtParamNameObjectStoreId + NS_LITERAL_CSTRING(", :") + - kStmtParamNameKey + NS_LITERAL_CSTRING(", :") + - kStmtParamNameFileIds + NS_LITERAL_CSTRING(", :") + - kStmtParamNameData + NS_LITERAL_CSTRING(");"), + "INSERT "_ns + optReplaceDirective + + nsLiteralCString("INTO object_data " + "(object_store_id, key, file_ids, data) " + "VALUES (:") + + kStmtParamNameObjectStoreId + ", :"_ns + kStmtParamNameKey + + ", :"_ns + kStmtParamNameFileIds + ", :"_ns + kStmtParamNameData + + ");"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -25518,12 +25449,12 @@ nsresult ObjectStoreGetRequestOp::DoDatabaseWork( limitClause.AppendInt(mLimit); } - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT file_ids, data " "FROM object_data " "WHERE object_store_id = :") + kStmtParamNameObjectStoreId + keyRangeClause + - NS_LITERAL_CSTRING(" ORDER BY key ASC") + limitClause; + " ORDER BY key ASC"_ns + limitClause; DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement(query, &stmt); @@ -25695,12 +25626,12 @@ nsresult ObjectStoreGetKeyRequestOp::DoDatabaseWork( limitClause.AppendInt(mLimit); } - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT key " "FROM object_data " "WHERE object_store_id = :") + kStmtParamNameObjectStoreId + keyRangeClause + - NS_LITERAL_CSTRING(" ORDER BY key ASC") + limitClause; + " ORDER BY key ASC"_ns + limitClause; DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement(query, &stmt); @@ -25818,10 +25749,9 @@ nsresult ObjectStoreDeleteRequestOp::DoDatabaseWork( GetBindingClauseForKeyRange(mParams.keyRange(), kColumnNameKey); rv = aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_data " - "WHERE object_store_id = :") + - kStmtParamNameObjectStoreId + keyRangeClause + - NS_LITERAL_CSTRING(";"), + nsLiteralCString("DELETE FROM object_data " + "WHERE object_store_id = :") + + kStmtParamNameObjectStoreId + keyRangeClause + ";"_ns, [this](mozIStorageStatement& stmt) { nsresult rv = stmt.BindInt64ByName(kStmtParamNameObjectStoreId, mParams.objectStoreId()); @@ -25892,22 +25822,21 @@ nsresult ObjectStoreClearRequestOp::DoDatabaseWork( // The parameter names are not used, parameters are bound by index only // locally in the same function. - rv = - objectStoreHasIndexes - ? DeleteObjectStoreDataTableRowsWithIndexes( - aConnection, mParams.objectStoreId(), Nothing()) - : aConnection->ExecuteCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM object_data " - "WHERE object_store_id = :object_store_id;"), - [this](mozIStorageStatement& stmt) { - nsresult rv = - stmt.BindInt64ByIndex(0, mParams.objectStoreId()); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } + rv = objectStoreHasIndexes + ? DeleteObjectStoreDataTableRowsWithIndexes( + aConnection, mParams.objectStoreId(), Nothing()) + : aConnection->ExecuteCachedStatement( + nsLiteralCString("DELETE FROM object_data " + "WHERE object_store_id = :object_store_id;"), + [this](mozIStorageStatement& stmt) { + nsresult rv = + stmt.BindInt64ByIndex(0, mParams.objectStoreId()); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } - return NS_OK; - }); + return NS_OK; + }); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -25930,7 +25859,7 @@ nsresult ObjectStoreCountRequestOp::DoDatabaseWork( const auto keyRangeClause = MaybeGetBindingClauseForKeyRange( mParams.optionalKeyRange(), kColumnNameKey); - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT count(*) " "FROM object_data " "WHERE object_store_id = :") + @@ -26086,12 +26015,12 @@ nsresult IndexGetRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) { limitClause.AppendInt(mLimit); } - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT file_ids, data " "FROM object_data " "INNER JOIN ") + indexTable + - NS_LITERAL_CSTRING( + nsLiteralCString( "AS index_table " "ON object_data.object_store_id = " "index_table.object_store_id " @@ -26250,10 +26179,10 @@ nsresult IndexGetKeyRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) { limitClause.AppendInt(mLimit); } - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT object_data_key " "FROM ") + - indexTable + NS_LITERAL_CSTRING("WHERE index_id = :") + + indexTable + "WHERE index_id = :"_ns + kStmtParamNameIndexId + keyRangeClause + limitClause; DatabaseConnection::CachedStatement stmt; @@ -26340,10 +26269,10 @@ nsresult IndexCountRequestOp::DoDatabaseWork(DatabaseConnection* aConnection) { const auto keyRangeClause = MaybeGetBindingClauseForKeyRange( mParams.optionalKeyRange(), kColumnNameValue); - nsCString query = NS_LITERAL_CSTRING( + nsCString query = nsLiteralCString( "SELECT count(*) " "FROM ") + - indexTable + NS_LITERAL_CSTRING("WHERE index_id = :") + + indexTable + "WHERE index_id = :"_ns + kStmtParamNameIndexId + keyRangeClause; DatabaseConnection::CachedStatement stmt; @@ -26638,8 +26567,8 @@ void ObjectStoreOpenOpHelper::PrepareKeyConditionClauses( } } - const nsAutoCString suffix = aDirectionClause + kOpenLimit + - NS_LITERAL_CSTRING(":") + kStmtParamNameLimit; + const nsAutoCString suffix = + aDirectionClause + kOpenLimit + ":"_ns + kStmtParamNameLimit; GetCursor().mContinueQueries.init( aQueryStart + keyRangeClause + suffix, @@ -26665,7 +26594,7 @@ void IndexOpenOpHelper::PrepareIndexKeyConditionClause( nsCString continueQuery, continueToQuery, continuePrimaryKeyQuery; continueToQuery = - aQueryStart + NS_LITERAL_CSTRING(" AND ") + + aQueryStart + " AND "_ns + GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterOrEquals : ComparisonOperator::LessOrEquals, kStmtParamNameCurrentKey); @@ -26674,47 +26603,45 @@ void IndexOpenOpHelper::PrepareIndexKeyConditionClause( case IDBCursorDirection::Next: case IDBCursorDirection::Prev: continueQuery = - aQueryStart + NS_LITERAL_CSTRING(" AND ") + + aQueryStart + " AND "_ns + GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterOrEquals : ComparisonOperator::LessOrEquals, kStmtParamNameCurrentKey) + - NS_LITERAL_CSTRING(" AND ( ") + + " AND ( "_ns + GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan : ComparisonOperator::LessThan, kStmtParamNameCurrentKey) + - NS_LITERAL_CSTRING(" OR ") + - GetKeyClause( - aObjectDataKeyPrefix + NS_LITERAL_CSTRING("object_data_key"), - isIncreasingOrder ? ComparisonOperator::GreaterThan - : ComparisonOperator::LessThan, - kStmtParamNameObjectStorePosition) + - NS_LITERAL_CSTRING(" ) "); + " OR "_ns + + GetKeyClause(aObjectDataKeyPrefix + "object_data_key"_ns, + isIncreasingOrder ? ComparisonOperator::GreaterThan + : ComparisonOperator::LessThan, + kStmtParamNameObjectStorePosition) + + " ) "_ns; continuePrimaryKeyQuery = aQueryStart + - NS_LITERAL_CSTRING( + nsLiteralCString( " AND (" "(") + GetSortKeyClause(ComparisonOperator::Equals, kStmtParamNameCurrentKey) + - NS_LITERAL_CSTRING(" AND ") + - GetKeyClause( - aObjectDataKeyPrefix + NS_LITERAL_CSTRING("object_data_key"), - isIncreasingOrder ? ComparisonOperator::GreaterOrEquals - : ComparisonOperator::LessOrEquals, - kStmtParamNameObjectStorePosition) + - NS_LITERAL_CSTRING(") OR ") + + " AND "_ns + + GetKeyClause(aObjectDataKeyPrefix + "object_data_key"_ns, + isIncreasingOrder ? ComparisonOperator::GreaterOrEquals + : ComparisonOperator::LessOrEquals, + kStmtParamNameObjectStorePosition) + + ") OR "_ns + GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan : ComparisonOperator::LessThan, kStmtParamNameCurrentKey) + - NS_LITERAL_CSTRING(")"); + ")"_ns; break; case IDBCursorDirection::Nextunique: case IDBCursorDirection::Prevunique: continueQuery = - aQueryStart + NS_LITERAL_CSTRING(" AND ") + + aQueryStart + " AND "_ns + GetSortKeyClause(isIncreasingOrder ? ComparisonOperator::GreaterThan : ComparisonOperator::LessThan, kStmtParamNameCurrentKey); @@ -26724,8 +26651,8 @@ void IndexOpenOpHelper::PrepareIndexKeyConditionClause( MOZ_CRASH("Should never get here!"); } - const nsAutoCString suffix = aDirectionClause + kOpenLimit + - NS_LITERAL_CSTRING(":") + kStmtParamNameLimit; + const nsAutoCString suffix = + aDirectionClause + kOpenLimit + ":"_ns + kStmtParamNameLimit; continueQuery += suffix; continueToQuery += suffix; if (!continuePrimaryKeyQuery.IsEmpty()) { @@ -26767,7 +26694,7 @@ nsresult CommonOpenOpHelper::ProcessStatementSteps( // TODO: We should somehow evaluate the effects of this. Maybe use a smaller // extra count than for ContinueOp? PopulateExtraResponses(aStmt, GetCursor().mMaxExtraCount, res.inspect(), - NS_LITERAL_CSTRING("OpenOp"), optPreviousKey); + "OpenOp"_ns, optPreviousKey); return NS_OK; } @@ -26782,8 +26709,8 @@ nsresult OpenOpHelper::DoDatabaseWork( const bool usingKeyRange = GetOptionalKeyRange().isSome(); - nsCString queryStart = NS_LITERAL_CSTRING("SELECT ") + kColumnNameKey + - NS_LITERAL_CSTRING( + nsCString queryStart = "SELECT "_ns + kColumnNameKey + + nsLiteralCString( ", file_ids, data " "FROM object_data " "WHERE object_store_id = :") + @@ -26836,8 +26763,8 @@ nsresult OpenOpHelper::DoDatabaseWork( const bool usingKeyRange = GetOptionalKeyRange().isSome(); - nsCString queryStart = NS_LITERAL_CSTRING("SELECT ") + kColumnNameKey + - NS_LITERAL_CSTRING( + nsCString queryStart = "SELECT "_ns + kColumnNameKey + + nsLiteralCString( " FROM object_data " "WHERE object_store_id = :") + kStmtParamNameId; @@ -26850,8 +26777,8 @@ nsresult OpenOpHelper::DoDatabaseWork( // Note: Changing the number or order of SELECT columns in the query will // require changes to CursorOpBase::PopulateResponseFromStatement. - const nsCString firstQuery = queryStart + keyRangeClause + directionClause + - kOpenLimit + NS_LITERAL_CSTRING("1"); + const nsCString firstQuery = + queryStart + keyRangeClause + directionClause + kOpenLimit + "1"_ns; DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement(firstQuery, &stmt); @@ -26889,29 +26816,26 @@ nsresult OpenOpHelper::DoDatabaseWork( const bool usingKeyRange = GetOptionalKeyRange().isSome(); - const auto indexTable = GetCursor().mUniqueIndex - ? NS_LITERAL_CSTRING("unique_index_data") - : NS_LITERAL_CSTRING("index_data"); + const auto indexTable = + GetCursor().mUniqueIndex ? "unique_index_data"_ns : "index_data"_ns; // The result of MakeColumnPairSelectionList is stored in a local variable, // since inlining it into the next statement causes a crash on some Mac OS X // builds (see https://bugzilla.mozilla.org/show_bug.cgi?id=1168606#c110). const auto columnPairSelectionList = MakeColumnPairSelectionList( - NS_LITERAL_CSTRING("index_table.value"), - NS_LITERAL_CSTRING("index_table.value_locale"), kColumnNameAliasSortKey, - GetCursor().IsLocaleAware()); - const nsCString sortColumnAlias = NS_LITERAL_CSTRING("SELECT ") + - columnPairSelectionList + - NS_LITERAL_CSTRING(", "); + "index_table.value"_ns, "index_table.value_locale"_ns, + kColumnNameAliasSortKey, GetCursor().IsLocaleAware()); + const nsCString sortColumnAlias = + "SELECT "_ns + columnPairSelectionList + ", "_ns; nsAutoCString queryStart = sortColumnAlias + - NS_LITERAL_CSTRING( + nsLiteralCString( "index_table.object_data_key, " "object_data.file_ids, " "object_data.data " "FROM ") + indexTable + - NS_LITERAL_CSTRING( + nsLiteralCString( " AS index_table " "JOIN object_data " "ON index_table.object_store_id = " @@ -26925,8 +26849,7 @@ nsresult OpenOpHelper::DoDatabaseWork( DatabaseOperationBase::MaybeGetBindingClauseForKeyRange( GetOptionalKeyRange(), kColumnNameAliasSortKey); - nsAutoCString directionClause = - NS_LITERAL_CSTRING(" ORDER BY ") + kColumnNameAliasSortKey; + nsAutoCString directionClause = " ORDER BY "_ns + kColumnNameAliasSortKey; switch (GetCursor().mDirection) { case IDBCursorDirection::Next: @@ -26996,33 +26919,29 @@ nsresult OpenOpHelper::DoDatabaseWork( const bool usingKeyRange = GetOptionalKeyRange().isSome(); - const auto table = GetCursor().mUniqueIndex - ? NS_LITERAL_CSTRING("unique_index_data") - : NS_LITERAL_CSTRING("index_data"); + const auto table = + GetCursor().mUniqueIndex ? "unique_index_data"_ns : "index_data"_ns; // The result of MakeColumnPairSelectionList is stored in a local variable, // since inlining it into the next statement causes a crash on some Mac OS X // builds (see https://bugzilla.mozilla.org/show_bug.cgi?id=1168606#c110). const auto columnPairSelectionList = MakeColumnPairSelectionList( - NS_LITERAL_CSTRING("value"), NS_LITERAL_CSTRING("value_locale"), - kColumnNameAliasSortKey, GetCursor().IsLocaleAware()); - const nsCString sortColumnAlias = NS_LITERAL_CSTRING("SELECT ") + - columnPairSelectionList + - NS_LITERAL_CSTRING(", "); + "value"_ns, "value_locale"_ns, kColumnNameAliasSortKey, + GetCursor().IsLocaleAware()); + const nsCString sortColumnAlias = + "SELECT "_ns + columnPairSelectionList + ", "_ns; nsAutoCString queryStart = sortColumnAlias + - NS_LITERAL_CSTRING( - "object_data_key " - " FROM ") + - table + NS_LITERAL_CSTRING(" WHERE index_id = :") + + "object_data_key " + " FROM "_ns + + table + " WHERE index_id = :"_ns + kStmtParamNameId; const auto keyRangeClause = DatabaseOperationBase::MaybeGetBindingClauseForKeyRange( GetOptionalKeyRange(), kColumnNameAliasSortKey); - nsAutoCString directionClause = - NS_LITERAL_CSTRING(" ORDER BY ") + kColumnNameAliasSortKey; + nsAutoCString directionClause = " ORDER BY "_ns + kColumnNameAliasSortKey; switch (GetCursor().mDirection) { case IDBCursorDirection::Next: @@ -27044,8 +26963,8 @@ nsresult OpenOpHelper::DoDatabaseWork( // Note: Changing the number or order of SELECT columns in the query will // require changes to CursorOpBase::PopulateResponseFromStatement. - const nsCString firstQuery = queryStart + keyRangeClause + directionClause + - kOpenLimit + NS_LITERAL_CSTRING("1"); + const nsCString firstQuery = + queryStart + keyRangeClause + directionClause + kOpenLimit + "1"_ns; DatabaseConnection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement(firstQuery, &stmt); @@ -27287,8 +27206,7 @@ nsresult Cursor::ContinueOp::DoDatabaseWork( } helper.PopulateExtraResponses(&*stmt, maxExtraCount, res.inspect(), - NS_LITERAL_CSTRING("ContinueOp"), - optPreviousKey); + "ContinueOp"_ns, optPreviousKey); return NS_OK; } diff --git a/dom/indexedDB/IDBDatabase.cpp b/dom/indexedDB/IDBDatabase.cpp index ead65b5b5195..a5eeb60042ae 100644 --- a/dom/indexedDB/IDBDatabase.cpp +++ b/dom/indexedDB/IDBDatabase.cpp @@ -547,9 +547,8 @@ RefPtr IDBDatabase::Transaction( }); if (foundIt == end) { // Not using nsPrintfCString in case "name" has embedded nulls. - aRv.ThrowNotFoundError( - NS_LITERAL_CSTRING("'") + NS_ConvertUTF16toUTF8(name) + - NS_LITERAL_CSTRING("' is not a known object store name")); + aRv.ThrowNotFoundError("'"_ns + NS_ConvertUTF16toUTF8(name) + + "' is not a known object store name"_ns); return nullptr; } diff --git a/dom/indexedDB/IDBFileRequest.cpp b/dom/indexedDB/IDBFileRequest.cpp index 14feb5dec46b..7fabeec10f81 100644 --- a/dom/indexedDB/IDBFileRequest.cpp +++ b/dom/indexedDB/IDBFileRequest.cpp @@ -60,7 +60,7 @@ void IDBFileRequest::FireProgressEvent(uint64_t aLoaded, uint64_t aTotal) { init.mTotal = aTotal; RefPtr event = - ProgressEvent::Constructor(this, NS_LITERAL_STRING("progress"), init); + ProgressEvent::Constructor(this, u"progress"_ns, init); DispatchTrustedEvent(event); } diff --git a/dom/indexedDB/PermissionRequestBase.cpp b/dom/indexedDB/PermissionRequestBase.cpp index 06da8886703c..38b7bc533418 100644 --- a/dom/indexedDB/PermissionRequestBase.cpp +++ b/dom/indexedDB/PermissionRequestBase.cpp @@ -25,7 +25,7 @@ namespace { #define IDB_PREFIX "indexedDB" #define TOPIC_PREFIX IDB_PREFIX "-permissions-" -const nsLiteralCString kPermissionString = NS_LITERAL_CSTRING(IDB_PREFIX); +const nsLiteralCString kPermissionString = nsLiteralCString(IDB_PREFIX); const char kPermissionPromptTopic[] = TOPIC_PREFIX "prompt"; diff --git a/dom/indexedDB/test/gtest/TestKey.cpp b/dom/indexedDB/test/gtest/TestKey.cpp index 8b59b81a0d1d..2f88a06ae0ef 100644 --- a/dom/indexedDB/test/gtest/TestKey.cpp +++ b/dom/indexedDB/test/gtest/TestKey.cpp @@ -193,10 +193,9 @@ static const uint8_t nonZeroLengthBinaryEncodedBuffer[] = {Key::eBinary, INSTANTIATE_TEST_CASE_P( DOM_IndexedDB_Key, TestWithParam_CString_ArrayBuffer_Pair, ::testing::Values( - std::make_pair(BufferAsCString(zeroLengthBinaryEncodedBuffer), - NS_LITERAL_CSTRING("")), + std::make_pair(BufferAsCString(zeroLengthBinaryEncodedBuffer), ""_ns), std::make_pair(BufferAsCString(nonZeroLengthBinaryEncodedBuffer), - NS_LITERAL_CSTRING("ab")))); + "ab"_ns))); TEST_P(TestWithParam_CString_String_Pair, Ctor_EncodedString) { const auto key = Key{GetParam().first}; @@ -213,10 +212,9 @@ static const uint8_t nonZeroLengthStringEncodedBuffer[] = {Key::eString, INSTANTIATE_TEST_CASE_P( DOM_IndexedDB_Key, TestWithParam_CString_String_Pair, ::testing::Values( - std::make_pair(BufferAsCString(zeroLengthStringEncodedBuffer), - NS_LITERAL_STRING("")), + std::make_pair(BufferAsCString(zeroLengthStringEncodedBuffer), u""_ns), std::make_pair(BufferAsCString(nonZeroLengthStringEncodedBuffer), - NS_LITERAL_STRING("ab")))); + u"ab"_ns))); TEST_P(TestWithParam_LiteralString, SetFromString) { auto key = Key{}; @@ -229,14 +227,10 @@ TEST_P(TestWithParam_LiteralString, SetFromString) { } INSTANTIATE_TEST_CASE_P(DOM_IndexedDB_Key, TestWithParam_LiteralString, - ::testing::Values(NS_LITERAL_STRING(""), - NS_LITERAL_STRING(u"abc"), - NS_LITERAL_STRING(u"\u007f"), - NS_LITERAL_STRING(u"\u0080"), - NS_LITERAL_STRING(u"\u1fff"), - NS_LITERAL_STRING(u"\u7fff"), - NS_LITERAL_STRING(u"\u8000"), - NS_LITERAL_STRING(u"\uffff"))); + ::testing::Values(u""_ns, u"abc"_ns, u"\u007f"_ns, + u"\u0080"_ns, u"\u1fff"_ns, + u"\u7fff"_ns, u"\u8000"_ns, + u"\uffff"_ns)); static JS::Value CreateArrayBufferValue(JSContext* const aContext, const size_t aSize, char* const aData) { @@ -264,7 +258,7 @@ TEST(DOM_IndexedDB_Key, SetFromJSVal_ZeroLengthArrayBuffer) Rooted rv2(context); EXPECT_EQ(NS_OK, key.ToJSVal(context, &rv2)); - CheckArrayBuffer(NS_LITERAL_CSTRING(""), rv2); + CheckArrayBuffer(""_ns, rv2); } template @@ -329,10 +323,8 @@ TEST_P(TestWithParam_ArrayBufferArray, SetFromJSVal) { const uint8_t element2[] = "foo"; INSTANTIATE_TEST_CASE_P( DOM_IndexedDB_Key, TestWithParam_ArrayBufferArray, - testing::Values(std::vector{}, - std::vector{NS_LITERAL_CSTRING("")}, - std::vector{NS_LITERAL_CSTRING(""), - BufferAsCString(element2)})); + testing::Values(std::vector{}, std::vector{""_ns}, + std::vector{""_ns, BufferAsCString(element2)})); static JS::Value CreateStringValue(JSContext* const context, const nsString& string) { @@ -379,11 +371,9 @@ TEST_P(TestWithParam_StringArray, SetFromJSVal) { INSTANTIATE_TEST_CASE_P( DOM_IndexedDB_Key, TestWithParam_StringArray, - testing::Values(std::vector{NS_LITERAL_STRING(""), - NS_LITERAL_STRING("abc\u0080\u1fff")}, - std::vector{ - NS_LITERAL_STRING("abc\u0080\u1fff"), - NS_LITERAL_STRING("abc\u0080\u1fff")})); + testing::Values(std::vector{u""_ns, u"abc\u0080\u1fff"_ns}, + std::vector{u"abc\u0080\u1fff"_ns, + u"abc\u0080\u1fff"_ns})); TEST(DOM_IndexedDB_Key, CompareKeys_NonZeroLengthArrayBuffer) { @@ -405,7 +395,7 @@ TEST(DOM_IndexedDB_Key, CompareKeys_NonZeroLengthArrayBuffer) EXPECT_EQ(0, Key::CompareKeys(first, second)); } -constexpr auto kTestLocale = NS_LITERAL_CSTRING("e"); +constexpr auto kTestLocale = "e"_ns; TEST(DOM_IndexedDB_Key, ToLocaleAwareKey_Empty) { diff --git a/dom/ipc/BrowserChild.cpp b/dom/ipc/BrowserChild.cpp index 7b7b0a81bcda..78e4b3bde3ec 100644 --- a/dom/ipc/BrowserChild.cpp +++ b/dom/ipc/BrowserChild.cpp @@ -2330,8 +2330,7 @@ mozilla::ipc::IPCResult BrowserChild::RecvDestroy() { // Message handlers are called from the event loop, so it better be safe to // run script. MOZ_ASSERT(nsContentUtils::IsSafeToRunScript()); - mBrowserChildMessageManager->DispatchTrustedEvent( - NS_LITERAL_STRING("unload")); + mBrowserChildMessageManager->DispatchTrustedEvent(u"unload"_ns); } nsCOMPtr observerService = diff --git a/dom/ipc/BrowserParent.cpp b/dom/ipc/BrowserParent.cpp index 0031c679c3d6..45a7fd0f39f9 100644 --- a/dom/ipc/BrowserParent.cpp +++ b/dom/ipc/BrowserParent.cpp @@ -567,10 +567,10 @@ void BrowserParent::AddWindowListeners() { mFrameElement->OwnerDoc()->GetWindow()) { nsCOMPtr eventTarget = window->GetTopWindowRoot(); if (eventTarget) { - eventTarget->AddEventListener(NS_LITERAL_STRING("MozUpdateWindowPos"), - this, false, false); - eventTarget->AddEventListener(NS_LITERAL_STRING("fullscreenchange"), - this, false, false); + eventTarget->AddEventListener(u"MozUpdateWindowPos"_ns, this, false, + false); + eventTarget->AddEventListener(u"fullscreenchange"_ns, this, false, + false); } } } @@ -582,10 +582,8 @@ void BrowserParent::RemoveWindowListeners() { mFrameElement->OwnerDoc()->GetWindow(); nsCOMPtr eventTarget = window->GetTopWindowRoot(); if (eventTarget) { - eventTarget->RemoveEventListener(NS_LITERAL_STRING("MozUpdateWindowPos"), - this, false); - eventTarget->RemoveEventListener(NS_LITERAL_STRING("fullscreenchange"), - this, false); + eventTarget->RemoveEventListener(u"MozUpdateWindowPos"_ns, this, false); + eventTarget->RemoveEventListener(u"fullscreenchange"_ns, this, false); } } } @@ -682,10 +680,8 @@ void BrowserParent::ActorDestroy(ActorDestroyReason why) { // was caused by OOM bool is_oom = false; if (crash_reason == "OOM" || crash_reason == "OOM!" || - StringBeginsWith(crash_reason, - NS_LITERAL_CSTRING("[unhandlable oom]")) || - StringBeginsWith(crash_reason, - NS_LITERAL_CSTRING("Unhandlable OOM"))) { + StringBeginsWith(crash_reason, "[unhandlable oom]"_ns) || + StringBeginsWith(crash_reason, "Unhandlable OOM"_ns)) { is_oom = true; } @@ -3541,9 +3537,9 @@ void BrowserParent::LayerTreeUpdate(const LayersObserverEpoch& aEpoch, RefPtr event = NS_NewDOMEvent(mFrameElement, nullptr, nullptr); if (aActive) { mHasPresented = true; - event->InitEvent(NS_LITERAL_STRING("MozLayerTreeReady"), true, false); + event->InitEvent(u"MozLayerTreeReady"_ns, true, false); } else { - event->InitEvent(NS_LITERAL_STRING("MozLayerTreeCleared"), true, false); + event->InitEvent(u"MozLayerTreeCleared"_ns, true, false); } event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; @@ -3567,7 +3563,7 @@ mozilla::ipc::IPCResult BrowserParent::RecvRemotePaintIsReady() { } RefPtr event = NS_NewDOMEvent(mFrameElement, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("MozAfterRemotePaint"), false, false); + event->InitEvent(u"MozAfterRemotePaint"_ns, false, false); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; mFrameElement->DispatchEvent(*event); diff --git a/dom/ipc/ContentChild.cpp b/dom/ipc/ContentChild.cpp index 17a8a1a1096a..7f0c16051ea6 100644 --- a/dom/ipc/ContentChild.cpp +++ b/dom/ipc/ContentChild.cpp @@ -554,7 +554,7 @@ class PendingInputEventHangAnnotator final : public BackgroundHangAnnotator { virtual void AnnotateHang(BackgroundHangAnnotations& aAnnotations) override { int32_t pending = ContentChild::GetSingleton()->GetPendingInputEvents(); if (pending > 0) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("PendingInput"), pending); + aAnnotations.AddAnnotation(u"PendingInput"_ns, pending); } } @@ -748,7 +748,7 @@ bool ContentChild::Init(MessageLoop* aIOLoop, base::ProcessId aParentPid, RefPtr printingProxy = nsPrintingProxy::GetInstance(); #endif - SetProcessName(NS_LITERAL_STRING("Web Content")); + SetProcessName(u"Web Content"_ns); #ifdef NIGHTLY_BUILD // NOTE: We have to register the annotator on the main thread, as annotators @@ -2581,16 +2581,16 @@ mozilla::ipc::IPCResult ContentChild::RecvRemoteType( // Update the process name so about:memory's process names are more obvious. if (aRemoteType.EqualsLiteral(FILE_REMOTE_TYPE)) { - SetProcessName(NS_LITERAL_STRING("file:// Content")); + SetProcessName(u"file:// Content"_ns); } else if (aRemoteType.EqualsLiteral(EXTENSION_REMOTE_TYPE)) { - SetProcessName(NS_LITERAL_STRING("WebExtensions")); + SetProcessName(u"WebExtensions"_ns); } else if (aRemoteType.EqualsLiteral(PRIVILEGEDABOUT_REMOTE_TYPE)) { - SetProcessName(NS_LITERAL_STRING("Privileged Content")); + SetProcessName(u"Privileged Content"_ns); } else if (aRemoteType.EqualsLiteral(LARGE_ALLOCATION_REMOTE_TYPE)) { - SetProcessName(NS_LITERAL_STRING("Large Allocation Web Content")); + SetProcessName(u"Large Allocation Web Content"_ns); } else if (RemoteTypePrefix(aRemoteType) .EqualsLiteral(FISSION_WEB_REMOTE_TYPE)) { - SetProcessName(NS_LITERAL_STRING("Isolated Web Content")); + SetProcessName(u"Isolated Web Content"_ns); } // else "prealloc", "web" or "webCOOP+COEP" type -> "Web Content" already set @@ -2668,8 +2668,7 @@ mozilla::ipc::IPCResult ContentChild::RecvNotifyProcessPriorityChanged( NS_ENSURE_TRUE(os, IPC_OK()); RefPtr props = new nsHashPropertyBag(); - props->SetPropertyAsInt32(NS_LITERAL_STRING("priority"), - static_cast(aPriority)); + props->SetPropertyAsInt32(u"priority"_ns, static_cast(aPriority)); os->NotifyObservers(static_cast(props), "ipc:process-priority-changed", nullptr); @@ -2849,8 +2848,7 @@ void ContentChild::ShutdownInternal() { // terminate an "unload" or "pagehide" event handler (which might be doing a // sync XHR, for example). CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IPCShutdownState, - NS_LITERAL_CSTRING("RecvShutdown")); + CrashReporter::Annotation::IPCShutdownState, "RecvShutdown"_ns); MOZ_ASSERT(NS_IsMainThread()); RefPtr mainThread = nsThreadManager::get().GetCurrentThread(); @@ -2910,12 +2908,11 @@ void ContentChild::ShutdownInternal() { CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::IPCShutdownState, - NS_LITERAL_CSTRING("SendFinishShutdown (sending)")); + "SendFinishShutdown (sending)"_ns); bool sent = SendFinishShutdown(); CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::IPCShutdownState, - sent ? NS_LITERAL_CSTRING("SendFinishShutdown (sent)") - : NS_LITERAL_CSTRING("SendFinishShutdown (failed)")); + sent ? "SendFinishShutdown (sent)"_ns : "SendFinishShutdown (failed)"_ns); } mozilla::ipc::IPCResult ContentChild::RecvUpdateWindow( diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index 083080ce1942..41780f2e487d 100644 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -1841,13 +1841,13 @@ void ContentParent::ActorDestroy(ActorDestroyReason why) { if (obs) { RefPtr props = new nsHashPropertyBag(); - props->SetPropertyAsUint64(NS_LITERAL_STRING("childID"), mChildID); + props->SetPropertyAsUint64(u"childID"_ns, mChildID); if (AbnormalShutdown == why) { - Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, - NS_LITERAL_CSTRING("content"), 1); + Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, "content"_ns, + 1); - props->SetPropertyAsBool(NS_LITERAL_STRING("abnormal"), true); + props->SetPropertyAsBool(u"abnormal"_ns, true); nsAutoString dumpID; // There's a window in which child processes can crash @@ -1859,7 +1859,7 @@ void ContentParent::ActorDestroy(ActorDestroyReason why) { if (!mCreatedPairedMinidumps) { if (mCrashReporter->GenerateCrashReport(OtherPid())) { // Propagate `isLikelyOOM`. - Unused << props->SetPropertyAsBool(NS_LITERAL_STRING("isLikelyOOM"), + Unused << props->SetPropertyAsBool(u"isLikelyOOM"_ns, mCrashReporter->IsLikelyOOM()); } } @@ -1872,7 +1872,7 @@ void ContentParent::ActorDestroy(ActorDestroyReason why) { } if (!dumpID.IsEmpty()) { - props->SetPropertyAsAString(NS_LITERAL_STRING("dumpID"), dumpID); + props->SetPropertyAsAString(u"dumpID"_ns, dumpID); } } nsAutoString cpId; @@ -2856,39 +2856,38 @@ bool ContentParent::InitInternal(ProcessPriority aInitialPriority) { { nsTArray registrations; - BlobURLProtocolHandler::ForEachBlobURL([&](BlobImpl* aBlobImpl, - nsIPrincipal* aPrincipal, - const nsACString& aURI, - bool aRevoked) { - nsAutoCString origin; - nsresult rv = aPrincipal->GetOrigin(origin); - if (NS_WARN_IF(NS_FAILED(rv))) { - return false; - } + BlobURLProtocolHandler::ForEachBlobURL( + [&](BlobImpl* aBlobImpl, nsIPrincipal* aPrincipal, + const nsACString& aURI, bool aRevoked) { + nsAutoCString origin; + nsresult rv = aPrincipal->GetOrigin(origin); + if (NS_WARN_IF(NS_FAILED(rv))) { + return false; + } - // We send all moz-extension Blob URL's to all content processes because - // content scripts mean that a moz-extension can live in any process. - // Same thing for system principal Blob URLs. - // Content Blob URL's are sent for content principals on-demand by - // AboutToLoadHttpFtpDocumentForChild and RemoteWorkerManager. - if (!StringBeginsWith(origin, NS_LITERAL_CSTRING("moz-extension://")) && - !aPrincipal->IsSystemPrincipal()) { - return true; - } + // We send all moz-extension Blob URL's to all content processes + // because content scripts mean that a moz-extension can live in any + // process. Same thing for system principal Blob URLs. Content Blob + // URL's are sent for content principals on-demand by + // AboutToLoadHttpFtpDocumentForChild and RemoteWorkerManager. + if (!StringBeginsWith(origin, "moz-extension://"_ns) && + !aPrincipal->IsSystemPrincipal()) { + return true; + } - IPCBlob ipcBlob; - rv = IPCBlobUtils::Serialize(aBlobImpl, this, ipcBlob); - if (NS_WARN_IF(NS_FAILED(rv))) { - return false; - } + IPCBlob ipcBlob; + rv = IPCBlobUtils::Serialize(aBlobImpl, this, ipcBlob); + if (NS_WARN_IF(NS_FAILED(rv))) { + return false; + } - registrations.AppendElement(BlobURLRegistrationData( - nsCString(aURI), ipcBlob, aPrincipal, aRevoked)); + registrations.AppendElement(BlobURLRegistrationData( + nsCString(aURI), ipcBlob, aPrincipal, aRevoked)); - rv = TransmitPermissionsForPrincipal(aPrincipal); - Unused << NS_WARN_IF(NS_FAILED(rv)); - return true; - }); + rv = TransmitPermissionsForPrincipal(aPrincipal); + Unused << NS_WARN_IF(NS_FAILED(rv)); + return true; + }); if (!registrations.IsEmpty()) { Unused << SendInitBlobURLs(registrations); @@ -3199,7 +3198,7 @@ ContentParent::GetName(nsAString& aName) { NS_IMETHODIMP ContentParent::GetState(nsIPropertyBag** aResult) { auto props = MakeRefPtr(); - props->SetPropertyAsAString(NS_LITERAL_STRING("remoteTypePrefix"), + props->SetPropertyAsAString(u"remoteTypePrefix"_ns, RemoteTypePrefix(mRemoteType)); *aResult = props.forget().downcast().take(); return NS_OK; @@ -3284,7 +3283,7 @@ ContentParent::Observe(nsISupports* aSubject, const char* aTopic, return NS_ERROR_NOT_AVAILABLE; } } else if (!strcmp(aTopic, NS_IPC_IOSERVICE_SET_CONNECTIVITY_TOPIC)) { - if (!SendSetConnectivity(NS_LITERAL_STRING("true").Equals(aData))) { + if (!SendSetConnectivity(u"true"_ns.Equals(aData))) { return NS_ERROR_NOT_AVAILABLE; } } else if (!strcmp(aTopic, NS_IPC_CAPTIVE_PORTAL_SET_STATE)) { @@ -3650,8 +3649,7 @@ void ContentParent::GeneratePairedMinidump(const char* aReason) { reason); // Generate the report and insert into the queue for submittal. - if (mCrashReporter->GenerateMinidumpAndPair( - this, nullptr, NS_LITERAL_CSTRING("browser"))) { + if (mCrashReporter->GenerateMinidumpAndPair(this, nullptr, "browser"_ns)) { mCreatedPairedMinidumps = mCrashReporter->FinalizeCrashReport(); } } @@ -4544,10 +4542,10 @@ mozilla::ipc::IPCResult ContentParent::RecvRecordingDeviceEvents( // recording-device-ipc-events needs to gather more information from content // process RefPtr props = new nsHashPropertyBag(); - props->SetPropertyAsUint64(NS_LITERAL_STRING("childID"), ChildID()); - props->SetPropertyAsBool(NS_LITERAL_STRING("isAudio"), aIsAudio); - props->SetPropertyAsBool(NS_LITERAL_STRING("isVideo"), aIsVideo); - props->SetPropertyAsAString(NS_LITERAL_STRING("requestURL"), aPageURL); + props->SetPropertyAsUint64(u"childID"_ns, ChildID()); + props->SetPropertyAsBool(u"isAudio"_ns, aIsAudio); + props->SetPropertyAsBool(u"isVideo"_ns, aIsVideo); + props->SetPropertyAsAString(u"requestURL"_ns, aPageURL); obs->NotifyObservers((nsIPropertyBag2*)props, "recording-device-ipc-events", aRecordingStatus.get()); @@ -5462,9 +5460,8 @@ void ContentParent::BroadcastBlobURLRegistration(const nsACString& aURI, uint64_t originHash = ComputeLoadedOriginHash(aPrincipal); - bool toBeSent = - StringBeginsWith(origin, NS_LITERAL_CSTRING("moz-extension://")) || - aPrincipal->IsSystemPrincipal(); + bool toBeSent = StringBeginsWith(origin, "moz-extension://"_ns) || + aPrincipal->IsSystemPrincipal(); nsCString uri(aURI); IPC::Principal principal(aPrincipal); @@ -5501,9 +5498,8 @@ void ContentParent::BroadcastBlobURLUnregistration( uint64_t originHash = ComputeLoadedOriginHash(aPrincipal); - bool toBeSent = - StringBeginsWith(origin, NS_LITERAL_CSTRING("moz-extension://")) || - aPrincipal->IsSystemPrincipal(); + bool toBeSent = StringBeginsWith(origin, "moz-extension://"_ns) || + aPrincipal->IsSystemPrincipal(); nsCString uri(aURI); diff --git a/dom/ipc/ContentParent.h b/dom/ipc/ContentParent.h index f6e00d50b5cd..d610b5c7143a 100644 --- a/dom/ipc/ContentParent.h +++ b/dom/ipc/ContentParent.h @@ -47,8 +47,7 @@ #include "DriverCrashGuard.h" #include "nsIReferrerInfo.h" -#define CHILD_PROCESS_SHUTDOWN_MESSAGE \ - NS_LITERAL_STRING("child-process-shutdown") +#define CHILD_PROCESS_SHUTDOWN_MESSAGE u"child-process-shutdown"_ns // These must match the similar ones in E10SUtils.jsm and ProcInfo.h. // Process names as reported by about:memory are defined in diff --git a/dom/ipc/JSActor.cpp b/dom/ipc/JSActor.cpp index 07f8cfa6b4d0..35aa750fecc6 100644 --- a/dom/ipc/JSActor.cpp +++ b/dom/ipc/JSActor.cpp @@ -69,13 +69,13 @@ struct MOZ_RAII AutoAnnotateMessageInCaseOfCrash { void JSActor::StartDestroy() { AutoAnnotateMessageInCaseOfCrash guard(/* aActorName = */ mName, - NS_LITERAL_CSTRING("")); + ""_ns); InvokeCallback(CallbackFunction::WillDestroy); } void JSActor::AfterDestroy() { AutoAnnotateMessageInCaseOfCrash guard(/* aActorName = */ mName, - NS_LITERAL_CSTRING("")); + ""_ns); InvokeCallback(CallbackFunction::DidDestroy); // Clear out & reject mPendingQueries RejectPendingQueries(); @@ -472,8 +472,7 @@ void JSActor::QueryHandler::ResolvedCallback(JSContext* aCx, msg.Append(NS_LossyConvertUTF16toASCII(mMessageName)); msg.AppendLiteral(": message reply cannot be cloned."); - auto exc = MakeRefPtr(msg, NS_ERROR_FAILURE, - NS_LITERAL_CSTRING("DataCloneError"), + auto exc = MakeRefPtr(msg, NS_ERROR_FAILURE, "DataCloneError"_ns, nullptr, nullptr); JS::Rooted val(aCx); diff --git a/dom/ipc/PreallocatedProcessManager.cpp b/dom/ipc/PreallocatedProcessManager.cpp index ead9001fe21a..b6b5fefa81a4 100644 --- a/dom/ipc/PreallocatedProcessManager.cpp +++ b/dom/ipc/PreallocatedProcessManager.cpp @@ -287,9 +287,9 @@ void PreallocatedProcessManagerImpl::RemoveBlocker(ContentParent* aParent) { MOZ_LOG(ContentParent::GetLog(), LogLevel::Debug, ("Blocked preallocation for %fms", (TimeStamp::Now() - mBlockingStartTime).ToMilliseconds())); - PROFILER_ADD_TEXT_MARKER( - "Process", NS_LITERAL_CSTRING("Blocked preallocation"), - JS::ProfilingCategoryPair::DOM, mBlockingStartTime, TimeStamp::Now()); + PROFILER_ADD_TEXT_MARKER("Process", "Blocked preallocation"_ns, + JS::ProfilingCategoryPair::DOM, mBlockingStartTime, + TimeStamp::Now()); if (IsEmpty()) { AllocateAfterDelay(); } diff --git a/dom/ipc/ProcessActor.cpp b/dom/ipc/ProcessActor.cpp index 1721b353cf9f..244f3ce53d1e 100644 --- a/dom/ipc/ProcessActor.cpp +++ b/dom/ipc/ProcessActor.cpp @@ -97,9 +97,8 @@ void ProcessActor::ConstructActor(const nsACString& aName, // Load the specific property from our module. JS::RootedValue ctor(cx); nsAutoCString ctorName(aName); - ctorName.Append(actorType == JSActor::Type::Parent - ? NS_LITERAL_CSTRING("Parent") - : NS_LITERAL_CSTRING("Child")); + ctorName.Append(actorType == JSActor::Type::Parent ? "Parent"_ns + : "Child"_ns); if (!JS_GetProperty(cx, exports, ctorName.get(), &ctor)) { aRv.NoteJSContextException(cx); return; diff --git a/dom/ipc/ProcessHangMonitor.cpp b/dom/ipc/ProcessHangMonitor.cpp index 78053cbfff24..601e595a092b 100644 --- a/dom/ipc/ProcessHangMonitor.cpp +++ b/dom/ipc/ProcessHangMonitor.cpp @@ -461,8 +461,7 @@ bool HangMonitorChild::InterruptCallback() { void HangMonitorChild::AnnotateHang(BackgroundHangAnnotations& aAnnotations) { if (mPaintWhileInterruptingJSActive) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("PaintWhileInterruptingJS"), - true); + aAnnotations.AddAnnotation(u"PaintWhileInterruptingJS"_ns, true); } } @@ -1157,8 +1156,7 @@ HangMonitoredProcess::TerminatePlugin() { uint32_t id = mHangData.get_PluginHangData().pluginId(); base::ProcessId contentPid = mHangData.get_PluginHangData().contentProcessId(); - plugins::TerminatePlugin(id, contentPid, NS_LITERAL_CSTRING("HangMonitor"), - mDumpId); + plugins::TerminatePlugin(id, contentPid, "HangMonitor"_ns, mDumpId); if (mActor) { mActor->CleanupPluginHang(id, false); diff --git a/dom/ipc/ProcessPriorityManager.cpp b/dom/ipc/ProcessPriorityManager.cpp index 5cf88ca4e2c4..a4aaae307450 100644 --- a/dom/ipc/ProcessPriorityManager.cpp +++ b/dom/ipc/ProcessPriorityManager.cpp @@ -446,7 +446,7 @@ void ProcessPriorityManagerImpl::ObserveContentParentDestroyed( NS_ENSURE_TRUE_VOID(props); uint64_t childID = CONTENT_PROCESS_ID_UNKNOWN; - props->GetPropertyAsUint64(NS_LITERAL_STRING("childID"), &childID); + props->GetPropertyAsUint64(u"childID"_ns, &childID); NS_ENSURE_TRUE_VOID(childID != CONTENT_PROCESS_ID_UNKNOWN); if (auto entry = mParticularManagers.Lookup(childID)) { @@ -511,13 +511,10 @@ void ParticularProcessPriorityManager::Init() { // This process may already hold the CPU lock; for example, our parent may // have acquired it on our behalf. - mHoldsCPUWakeLock = IsHoldingWakeLock(NS_LITERAL_STRING("cpu")); - mHoldsHighPriorityWakeLock = - IsHoldingWakeLock(NS_LITERAL_STRING("high-priority")); - mHoldsPlayingAudioWakeLock = - IsHoldingWakeLock(NS_LITERAL_STRING("audio-playing")); - mHoldsPlayingVideoWakeLock = - IsHoldingWakeLock(NS_LITERAL_STRING("video-playing")); + mHoldsCPUWakeLock = IsHoldingWakeLock(u"cpu"_ns); + mHoldsHighPriorityWakeLock = IsHoldingWakeLock(u"high-priority"_ns); + mHoldsPlayingAudioWakeLock = IsHoldingWakeLock(u"audio-playing"_ns); + mHoldsPlayingVideoWakeLock = IsHoldingWakeLock(u"video-playing"_ns); LOGP( "Done starting up. mHoldsCPUWakeLock=%d, " @@ -923,7 +920,7 @@ ProcessPriorityManagerChild::Observe(nsISupports* aSubject, const char* aTopic, NS_ENSURE_TRUE(props, NS_OK); int32_t priority = static_cast(PROCESS_PRIORITY_UNKNOWN); - props->GetPropertyAsInt32(NS_LITERAL_STRING("priority"), &priority); + props->GetPropertyAsInt32(u"priority"_ns, &priority); NS_ENSURE_TRUE(ProcessPriority(priority) != PROCESS_PRIORITY_UNKNOWN, NS_OK); mCachedPriority = static_cast(priority); diff --git a/dom/ipc/SharedMap.cpp b/dom/ipc/SharedMap.cpp index 683e74528eb6..c9672cedf0dc 100644 --- a/dom/ipc/SharedMap.cpp +++ b/dom/ipc/SharedMap.cpp @@ -129,8 +129,8 @@ void SharedMap::Update(const FileDescriptor& aMapFile, size_t aMapSize, fallible); } - RefPtr event = SharedMapChangeEvent::Constructor( - this, NS_LITERAL_STRING("change"), init); + RefPtr event = + SharedMapChangeEvent::Constructor(this, u"change"_ns, init); event->SetTrusted(true); DispatchEvent(*event); diff --git a/dom/ipc/WindowGlobalActor.cpp b/dom/ipc/WindowGlobalActor.cpp index cc2f652fa31a..697d0cc0b4df 100644 --- a/dom/ipc/WindowGlobalActor.cpp +++ b/dom/ipc/WindowGlobalActor.cpp @@ -212,9 +212,8 @@ void WindowGlobalActor::ConstructActor(const nsACString& aName, // Load the specific property from our module. JS::RootedValue ctor(cx); nsAutoCString ctorName(aName); - ctorName.Append(actorType == JSActor::Type::Parent - ? NS_LITERAL_CSTRING("Parent") - : NS_LITERAL_CSTRING("Child")); + ctorName.Append(actorType == JSActor::Type::Parent ? "Parent"_ns + : "Child"_ns); if (!JS_GetProperty(cx, exports, ctorName.get(), &ctor)) { aRv.NoteJSContextException(cx); return; diff --git a/dom/ipc/WindowGlobalChild.cpp b/dom/ipc/WindowGlobalChild.cpp index f93c1083a7f1..c8491bcf4c14 100644 --- a/dom/ipc/WindowGlobalChild.cpp +++ b/dom/ipc/WindowGlobalChild.cpp @@ -519,7 +519,7 @@ mozilla::ipc::IPCResult WindowGlobalChild::RecvDispatchSecurityPolicyViolation( } RefPtr event = SecurityPolicyViolationEvent::Constructor( - doc, NS_LITERAL_STRING("securitypolicyviolation"), violationEvent); + doc, u"securitypolicyviolation"_ns, violationEvent); event->SetTrusted(true); doc->DispatchEvent(*event, IgnoreErrors()); return IPC_OK(); diff --git a/dom/ipc/WindowGlobalParent.cpp b/dom/ipc/WindowGlobalParent.cpp index 4da750763e39..3c56b5718657 100644 --- a/dom/ipc/WindowGlobalParent.cpp +++ b/dom/ipc/WindowGlobalParent.cpp @@ -352,7 +352,7 @@ mozilla::ipc::IPCResult WindowGlobalParent::RecvUpdateDocumentTitle( return IPC_OK(); } - (new AsyncEventDispatcher(frameElement, NS_LITERAL_STRING("pagetitlechanged"), + (new AsyncEventDispatcher(frameElement, u"pagetitlechanged"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes)) ->RunDOMEventWhenSafe(); diff --git a/dom/jsurl/nsJSProtocolHandler.cpp b/dom/jsurl/nsJSProtocolHandler.cpp index 3fe9926574ae..b96f14afdec3 100644 --- a/dom/jsurl/nsJSProtocolHandler.cpp +++ b/dom/jsurl/nsJSProtocolHandler.cpp @@ -435,9 +435,9 @@ nsresult nsJSChannel::Init(nsIURI* aURI, nsILoadInfo* aLoadInfo) { // and the underlying Input Stream will not be created... nsCOMPtr channel; RefPtr thunk = mIOThunk; - rv = NS_NewInputStreamChannelInternal( - getter_AddRefs(channel), aURI, thunk.forget(), - NS_LITERAL_CSTRING("text/html"), EmptyCString(), aLoadInfo); + rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aURI, + thunk.forget(), "text/html"_ns, + EmptyCString(), aLoadInfo); NS_ENSURE_SUCCESS(rv, rv); rv = mIOThunk->Init(aURI); @@ -446,8 +446,7 @@ nsresult nsJSChannel::Init(nsIURI* aURI, nsILoadInfo* aLoadInfo) { mPropertyBag = do_QueryInterface(channel); nsCOMPtr writableBag = do_QueryInterface(channel); if (writableBag && jsURI->GetBaseURI()) { - writableBag->SetPropertyAsInterface(NS_LITERAL_STRING("baseURI"), - jsURI->GetBaseURI()); + writableBag->SetPropertyAsInterface(u"baseURI"_ns, jsURI->GetBaseURI()); } } diff --git a/dom/l10n/DOMLocalization.cpp b/dom/l10n/DOMLocalization.cpp index f7ec2f138fd3..cf08222e04e8 100644 --- a/dom/l10n/DOMLocalization.cpp +++ b/dom/l10n/DOMLocalization.cpp @@ -550,60 +550,55 @@ void DOMLocalization::ReportL10nOverlaysErrors( for (auto& error : aErrors) { if (error.mCode.WasPassed()) { - msg = NS_LITERAL_STRING("[fluent-dom] "); + msg = u"[fluent-dom] "_ns; switch (error.mCode.Value()) { case L10nOverlays_Binding::ERROR_FORBIDDEN_TYPE: - msg += NS_LITERAL_STRING("An element of forbidden type \"") + + msg += u"An element of forbidden type \""_ns + error.mTranslatedElementName.Value() + - NS_LITERAL_STRING( - "\" was found in the translation. Only safe text-level " + nsLiteralString( + u"\" was found in the translation. Only safe text-level " "elements and elements with data-l10n-name are allowed."); break; case L10nOverlays_Binding::ERROR_NAMED_ELEMENT_MISSING: - msg += NS_LITERAL_STRING("An element named \"") + - error.mL10nName.Value() + - NS_LITERAL_STRING("\" wasn't found in the source."); + msg += u"An element named \""_ns + error.mL10nName.Value() + + u"\" wasn't found in the source."_ns; break; case L10nOverlays_Binding::ERROR_NAMED_ELEMENT_TYPE_MISMATCH: - msg += NS_LITERAL_STRING("An element named \"") + - error.mL10nName.Value() + - NS_LITERAL_STRING( - "\" was found in the translation but its type ") + + msg += u"An element named \""_ns + error.mL10nName.Value() + + nsLiteralString( + u"\" was found in the translation but its type ") + error.mTranslatedElementName.Value() + - NS_LITERAL_STRING( - " didn't match the element found in the source ") + - error.mSourceElementName.Value() + NS_LITERAL_STRING("."); + nsLiteralString( + u" didn't match the element found in the source ") + + error.mSourceElementName.Value() + u"."_ns; break; case L10nOverlays_Binding::ERROR_TRANSLATED_ELEMENT_DISCONNECTED: - msg += NS_LITERAL_STRING("The element using message \"") + - error.mL10nName.Value() + - NS_LITERAL_STRING( - "\" was removed from the DOM when translating its \"") + - error.mTranslatedElementName.Value() + - NS_LITERAL_STRING("\" parent."); + msg += u"The element using message \""_ns + error.mL10nName.Value() + + nsLiteralString( + u"\" was removed from the DOM when translating its \"") + + error.mTranslatedElementName.Value() + u"\" parent."_ns; break; case L10nOverlays_Binding::ERROR_TRANSLATED_ELEMENT_DISALLOWED_DOM: - msg += NS_LITERAL_STRING( - "While translating an element with fluent ID \"") + - error.mL10nName.Value() + - NS_LITERAL_STRING("\" a child element of type \"") + + msg += nsLiteralString( + u"While translating an element with fluent ID \"") + + error.mL10nName.Value() + u"\" a child element of type \""_ns + error.mTranslatedElementName.Value() + - NS_LITERAL_STRING( - "\" was removed. Either the fluent message " + nsLiteralString( + u"\" was removed. Either the fluent message " "does not contain markup, or it does not contain markup " "of this type."); break; case L10nOverlays_Binding::ERROR_UNKNOWN: default: - msg += NS_LITERAL_STRING( - "Unknown error happened while translating an element."); + msg += nsLiteralString( + u"Unknown error happened while translating an element."); break; } nsPIDOMWindowInner* innerWindow = GetParentObject()->AsInnerWindow(); Document* doc = innerWindow ? innerWindow->GetExtantDoc() : nullptr; if (doc) { nsContentUtils::ReportToConsoleNonLocalized( - msg, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), doc); + msg, nsIScriptError::warningFlag, "DOM"_ns, doc); } else { NS_WARNING("Failed to report l10n DOM Overlay errors to console."); } @@ -620,8 +615,7 @@ void DOMLocalization::ConvertStringToL10nArgs(const nsString& aInput, // Once we get Record::Init(const nsAString& aJSON), we'll switch to // that. L10nArgsHelperDict helperDict; - if (!helperDict.Init(NS_LITERAL_STRING("{\"args\": ") + aInput + - NS_LITERAL_STRING("}"))) { + if (!helperDict.Init(u"{\"args\": "_ns + aInput + u"}"_ns)) { aRv.Throw(NS_ERROR_UNEXPECTED); return; } diff --git a/dom/l10n/tests/gtest/TestL10nOverlays.cpp b/dom/l10n/tests/gtest/TestL10nOverlays.cpp index 0f6925948c9f..d52ae019186f 100644 --- a/dom/l10n/tests/gtest/TestL10nOverlays.cpp +++ b/dom/l10n/tests/gtest/TestL10nOverlays.cpp @@ -54,10 +54,8 @@ TEST(DOM_L10n_Overlays, Initial) // RefPtr elem = doc->CreateHTMLElement(nsGkAtoms::div); RefPtr span = doc->CreateHTMLElement(nsGkAtoms::a); - span->SetAttribute(NS_LITERAL_STRING("data-l10n-name"), - NS_LITERAL_STRING("link"), rv); - span->SetAttribute(NS_LITERAL_STRING("href"), - NS_LITERAL_STRING("https://www.mozilla.org"), rv); + span->SetAttribute(u"data-l10n-name"_ns, u"link"_ns, rv); + span->SetAttribute(u"href"_ns, u"https://www.mozilla.org"_ns, rv); elem->AppendChild(*span, rv); // 3. Create an L10nMessage with a translation for the element. diff --git a/dom/localstorage/ActorsParent.cpp b/dom/localstorage/ActorsParent.cpp index 35928c139bcd..9244e63f2bfc 100644 --- a/dom/localstorage/ActorsParent.cpp +++ b/dom/localstorage/ActorsParent.cpp @@ -297,7 +297,7 @@ int32_t MakeSchemaVersion(uint32_t aMajorSchemaVersion, nsCString GetArchivedOriginHashKey(const nsACString& aOriginSuffix, const nsACString& aOriginNoSuffix) { - return aOriginSuffix + NS_LITERAL_CSTRING(":") + aOriginNoSuffix; + return aOriginSuffix + ":"_ns + aOriginNoSuffix; } nsresult CreateTables(mozIStorageConnection* aConnection) { @@ -306,26 +306,26 @@ nsresult CreateTables(mozIStorageConnection* aConnection) { // Table `database` nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE database" - "( origin TEXT NOT NULL" - ", usage INTEGER NOT NULL DEFAULT 0" - ", last_vacuum_time INTEGER NOT NULL DEFAULT 0" - ", last_analyze_time INTEGER NOT NULL DEFAULT 0" - ", last_vacuum_size INTEGER NOT NULL DEFAULT 0" - ");")); + nsLiteralCString("CREATE TABLE database" + "( origin TEXT NOT NULL" + ", usage INTEGER NOT NULL DEFAULT 0" + ", last_vacuum_time INTEGER NOT NULL DEFAULT 0" + ", last_analyze_time INTEGER NOT NULL DEFAULT 0" + ", last_vacuum_size INTEGER NOT NULL DEFAULT 0" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `data` rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE data" - "( key TEXT PRIMARY KEY" - ", value TEXT NOT NULL" - ", utf16Length INTEGER NOT NULL DEFAULT 0" - ", compressed INTEGER NOT NULL DEFAULT 0" - ", lastAccessTime INTEGER NOT NULL DEFAULT 0" - ");")); + nsLiteralCString("CREATE TABLE data" + "( key TEXT PRIMARY KEY" + ", value TEXT NOT NULL" + ", utf16Length INTEGER NOT NULL DEFAULT 0" + ", compressed INTEGER NOT NULL DEFAULT 0" + ", lastAccessTime INTEGER NOT NULL DEFAULT 0" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -342,13 +342,13 @@ nsresult UpgradeSchemaFrom1_0To2_0(mozIStorageConnection* aConnection) { AssertIsOnIOThread(); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConnection->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE database ADD COLUMN usage INTEGER NOT NULL DEFAULT 0;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aConnection->ExecuteSimpleSQL(nsLiteralCString( "UPDATE database " "SET usage = (SELECT total(utf16Length(key) + utf16Length(value)) " "FROM data);")); @@ -368,14 +368,14 @@ nsresult UpgradeSchemaFrom2_0To3_0(mozIStorageConnection* aConnection) { AssertIsOnIOThread(); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConnection->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE data ADD COLUMN utf16Length INTEGER NOT NULL DEFAULT 0;")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE data SET utf16Length = utf16Length(value);")); + "UPDATE data SET utf16Length = utf16Length(value);"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -404,8 +404,7 @@ nsresult SetDefaultPragmas(mozIStorageConnection* aConnection) { MOZ_ASSERT(!NS_IsMainThread()); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA synchronous = FULL;")); + nsresult rv = aConnection->ExecuteSimpleSQL("PRAGMA synchronous = FULL;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -506,10 +505,10 @@ nsresult CreateStorageConnection(nsIFile* aDBFile, nsIFile* aUsageFile, #ifdef LS_MOBILE // Turn on full auto_vacuum mode to reclaim disk space on mobile // devices (at the cost of some COMMIT speed). - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = FULL;") + "PRAGMA auto_vacuum = FULL;"_ns #else // Turn on incremental auto_vacuum mode on desktop builds. - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = INCREMENTAL;") + "PRAGMA auto_vacuum = INCREMENTAL;"_ns #endif ); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -531,14 +530,14 @@ nsresult CreateStorageConnection(nsIFile* aDBFile, nsIFile* aUsageFile, nsCOMPtr stmt; nsresult rv = connection->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO database (origin) " - "VALUES (:origin)"), + nsLiteralCString("INSERT INTO database (origin) " + "VALUES (:origin)"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("origin"), aOrigin); + rv = stmt->BindUTF8StringByName("origin"_ns, aOrigin); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -605,22 +604,20 @@ nsresult CreateStorageConnection(nsIFile* aDBFile, nsIFile* aUsageFile, nsCOMPtr vacuumTimeStmt; rv = connection->CreateStatement( - NS_LITERAL_CSTRING("UPDATE database " - "SET last_vacuum_time = :time" - ", last_vacuum_size = :size;"), + nsLiteralCString("UPDATE database " + "SET last_vacuum_time = :time" + ", last_vacuum_size = :size;"), getter_AddRefs(vacuumTimeStmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = vacuumTimeStmt->BindInt64ByName(NS_LITERAL_CSTRING("time"), - vacuumTime); + rv = vacuumTimeStmt->BindInt64ByName("time"_ns, vacuumTime); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = - vacuumTimeStmt->BindInt64ByName(NS_LITERAL_CSTRING("size"), fileSize); + rv = vacuumTimeStmt->BindInt64ByName("size"_ns, fileSize); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -640,7 +637,7 @@ nsresult GetStorageConnection(const nsAString& aDatabaseFilePath, mozIStorageConnection** aConnection) { AssertIsOnConnectionThread(); MOZ_ASSERT(!aDatabaseFilePath.IsEmpty()); - MOZ_ASSERT(StringEndsWith(aDatabaseFilePath, NS_LITERAL_STRING(".sqlite"))); + MOZ_ASSERT(StringEndsWith(aDatabaseFilePath, u".sqlite"_ns)); MOZ_ASSERT(aConnection); auto databaseFileOrErr = QM_NewLocalFile(aDatabaseFilePath); @@ -789,14 +786,13 @@ nsresult AttachArchiveDatabase(const nsAString& aStoragePath, } nsCOMPtr stmt; - rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("ATTACH DATABASE :path AS archive;"), - getter_AddRefs(stmt)); + rv = aConnection->CreateStatement("ATTACH DATABASE :path AS archive;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("path"), path); + rv = stmt->BindStringByName("path"_ns, path); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -813,8 +809,7 @@ nsresult DetachArchiveDatabase(mozIStorageConnection* aConnection) { AssertIsOnIOThread(); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DETACH DATABASE archive")); + nsresult rv = aConnection->ExecuteSimpleSQL("DETACH DATABASE archive"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -879,7 +874,7 @@ nsresult SetShadowJournalMode(mozIStorageConnection* aConnection) { // Set the threshold for auto-checkpointing the WAL. We don't want giant // logs slowing down us. - rv = aConnection->CreateStatement(NS_LITERAL_CSTRING("PRAGMA page_size;"), + rv = aConnection->CreateStatement("PRAGMA page_size;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -904,8 +899,8 @@ nsresult SetShadowJournalMode(mozIStorageConnection* aConnection) { nsAutoCString pageCount; pageCount.AppendInt(static_cast(kShadowMaxWALSize / pageSize)); - rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA wal_autocheckpoint = ") + pageCount); + rv = aConnection->ExecuteSimpleSQL("PRAGMA wal_autocheckpoint = "_ns + + pageCount); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -915,14 +910,13 @@ nsresult SetShadowJournalMode(mozIStorageConnection* aConnection) { nsAutoCString sizeLimit; sizeLimit.AppendInt(kShadowJournalSizeLimit); - rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA journal_size_limit = ") + sizeLimit); + rv = aConnection->ExecuteSimpleSQL("PRAGMA journal_size_limit = "_ns + + sizeLimit); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } else { - rv = aConnection->ExecuteSimpleSQL(journalModeQueryStart + - NS_LITERAL_CSTRING("truncate")); + rv = aConnection->ExecuteSimpleSQL(journalModeQueryStart + "truncate"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1067,14 +1061,13 @@ nsresult AttachShadowDatabase(const nsAString& aBasePath, } nsCOMPtr stmt; - rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("ATTACH DATABASE :path AS shadow;"), - getter_AddRefs(stmt)); + rv = aConnection->CreateStatement("ATTACH DATABASE :path AS shadow;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("path"), path); + rv = stmt->BindStringByName("path"_ns, path); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1091,8 +1084,7 @@ nsresult DetachShadowDatabase(mozIStorageConnection* aConnection) { AssertIsOnConnectionThread(); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DETACH DATABASE shadow")); + nsresult rv = aConnection->ExecuteSimpleSQL("DETACH DATABASE shadow"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3066,8 +3058,8 @@ nsresult LoadArchivedOrigins() { nsCOMPtr stmt; rv = connection->CreateStatement( - NS_LITERAL_CSTRING("SELECT DISTINCT originAttributes, originKey " - "FROM webappsstore2;"), + nsLiteralCString("SELECT DISTINCT originAttributes, originKey " + "FROM webappsstore2;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3118,11 +3110,11 @@ nsresult GetUsage(mozIStorageConnection* aConnection, nsCOMPtr stmt; if (aArchivedOriginScope) { rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("SELECT " - "total(utf16Length(key) + utf16Length(value)) " - "FROM webappsstore2 " - "WHERE originKey = :originKey " - "AND originAttributes = :originAttributes;"), + nsLiteralCString("SELECT " + "total(utf16Length(key) + utf16Length(value)) " + "FROM webappsstore2 " + "WHERE originKey = :originKey " + "AND originAttributes = :originAttributes;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3130,8 +3122,8 @@ nsresult GetUsage(mozIStorageConnection* aConnection, rv = aArchivedOriginScope->BindToStatement(stmt); } else { - rv = aConnection->CreateStatement(NS_LITERAL_CSTRING("SELECT usage " - "FROM database"), + rv = aConnection->CreateStatement(nsLiteralCString("SELECT usage " + "FROM database"), getter_AddRefs(stmt)); } if (NS_WARN_IF(NS_FAILED(rv))) { @@ -3815,14 +3807,14 @@ nsresult ConnectionWriteOptimizer::Perform(Connection* aConnection, Connection::CachedStatement stmt; rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("UPDATE database " - "SET usage = usage + :delta"), + nsLiteralCString("UPDATE database " + "SET usage = usage + :delta"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("delta"), mTotalDelta); + rv = stmt->BindInt64ByName("delta"_ns, mTotalDelta); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3832,8 +3824,8 @@ nsresult ConnectionWriteOptimizer::Perform(Connection* aConnection, return rv; } - rv = aConnection->GetCachedStatement(NS_LITERAL_CSTRING("SELECT usage " - "FROM database"), + rv = aConnection->GetCachedStatement(nsLiteralCString("SELECT usage " + "FROM database"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3867,7 +3859,7 @@ nsresult ConnectionWriteOptimizer::PerformInsertOrUpdate( Connection::CachedStatement stmt; nsresult rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT OR REPLACE INTO data (key, value, utf16Length, compressed) " "VALUES(:key, :value, :utf16Length, :compressed)"), &stmt); @@ -3875,24 +3867,22 @@ nsresult ConnectionWriteOptimizer::PerformInsertOrUpdate( return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), aKey); + rv = stmt->BindStringByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), aValue); + rv = stmt->BindUTF8StringByName("value"_ns, aValue); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("utf16Length"), - aValue.UTF16Length()); + rv = stmt->BindInt32ByName("utf16Length"_ns, aValue.UTF16Length()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("compressed"), - aValue.IsCompressed()); + rv = stmt->BindInt32ByName("compressed"_ns, aValue.IsCompressed()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3907,7 +3897,7 @@ nsresult ConnectionWriteOptimizer::PerformInsertOrUpdate( } rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT OR REPLACE INTO shadow.webappsstore2 " "(originAttributes, originKey, scope, key, value) " "VALUES (:originAttributes, :originKey, :scope, :key, :value) "), @@ -3927,12 +3917,12 @@ nsresult ConnectionWriteOptimizer::PerformInsertOrUpdate( nsCString scope = Scheme0Scope(archivedOriginScope->OriginSuffix(), archivedOriginScope->OriginNoSuffix()); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("scope"), scope); + rv = stmt->BindUTF8StringByName("scope"_ns, scope); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), aKey); + rv = stmt->BindStringByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3942,9 +3932,9 @@ nsresult ConnectionWriteOptimizer::PerformInsertOrUpdate( if (NS_WARN_IF(!SnappyUncompress(aValue, value))) { return NS_ERROR_FAILURE; } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), value); + rv = stmt->BindUTF8StringByName("value"_ns, value); } else { - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), aValue); + rv = stmt->BindUTF8StringByName("value"_ns, aValue); } if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -3966,14 +3956,14 @@ nsresult ConnectionWriteOptimizer::PerformDelete(Connection* aConnection, Connection::CachedStatement stmt; nsresult rv = - aConnection->GetCachedStatement(NS_LITERAL_CSTRING("DELETE FROM data " - "WHERE key = :key;"), + aConnection->GetCachedStatement(nsLiteralCString("DELETE FROM data " + "WHERE key = :key;"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), aKey); + rv = stmt->BindStringByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3988,10 +3978,10 @@ nsresult ConnectionWriteOptimizer::PerformDelete(Connection* aConnection, } rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM shadow.webappsstore2 " - "WHERE originAttributes = :originAttributes " - "AND originKey = :originKey " - "AND key = :key;"), + nsLiteralCString("DELETE FROM shadow.webappsstore2 " + "WHERE originAttributes = :originAttributes " + "AND originKey = :originKey " + "AND key = :key;"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -4002,7 +3992,7 @@ nsresult ConnectionWriteOptimizer::PerformDelete(Connection* aConnection, return rv; } - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), aKey); + rv = stmt->BindStringByName("key"_ns, aKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4021,8 +4011,7 @@ nsresult ConnectionWriteOptimizer::PerformTruncate(Connection* aConnection, MOZ_ASSERT(aConnection); Connection::CachedStatement stmt; - nsresult rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM data;"), &stmt); + nsresult rv = aConnection->GetCachedStatement("DELETE FROM data;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4037,9 +4026,9 @@ nsresult ConnectionWriteOptimizer::PerformTruncate(Connection* aConnection, } rv = aConnection->GetCachedStatement( - NS_LITERAL_CSTRING("DELETE FROM shadow.webappsstore2 " - "WHERE originAttributes = :originAttributes " - "AND originKey = :originKey;"), + nsLiteralCString("DELETE FROM shadow.webappsstore2 " + "WHERE originAttributes = :originAttributes " + "AND originKey = :originKey;"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -4456,10 +4445,9 @@ nsresult Connection::GetCachedStatement(const nsACString& aQuery, nsCString msg; MOZ_ALWAYS_SUCCEEDS(mStorageConnection->GetLastErrorString(msg)); - nsAutoCString error = - NS_LITERAL_CSTRING("The statement '") + aQuery + - NS_LITERAL_CSTRING("' failed to compile with the error message '") + - msg + NS_LITERAL_CSTRING("'."); + nsAutoCString error = "The statement '"_ns + aQuery + + "' failed to compile with the error message '"_ns + + msg + "'."_ns; NS_WARNING(error.get()); #endif @@ -4478,8 +4466,7 @@ nsresult Connection::BeginWriteTransaction() { MOZ_ASSERT(mStorageConnection); CachedStatement stmt; - nsresult rv = - GetCachedStatement(NS_LITERAL_CSTRING("BEGIN IMMEDIATE;"), &stmt); + nsresult rv = GetCachedStatement("BEGIN IMMEDIATE;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4497,7 +4484,7 @@ nsresult Connection::CommitWriteTransaction() { MOZ_ASSERT(mStorageConnection); CachedStatement stmt; - nsresult rv = GetCachedStatement(NS_LITERAL_CSTRING("COMMIT;"), &stmt); + nsresult rv = GetCachedStatement("COMMIT;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4515,7 +4502,7 @@ nsresult Connection::RollbackWriteTransaction() { MOZ_ASSERT(mStorageConnection); CachedStatement stmt; - nsresult rv = GetCachedStatement(NS_LITERAL_CSTRING("ROLLBACK;"), &stmt); + nsresult rv = GetCachedStatement("ROLLBACK;"_ns, &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -7522,23 +7509,21 @@ nsresult PrepareDatastoreOp::DatabaseWork() { nsCOMPtr function = new CompressFunction(); - rv = - connection->CreateFunction(NS_LITERAL_CSTRING("compress"), 1, function); + rv = connection->CreateFunction("compress"_ns, 1, function); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } function = new CompressibleFunction(); - rv = connection->CreateFunction(NS_LITERAL_CSTRING("compressible"), 1, - function); + rv = connection->CreateFunction("compressible"_ns, 1, function); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } nsCOMPtr stmt; rv = connection->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT INTO data (key, value, utf16Length, compressed) " "SELECT key, compress(value), utf16Length(value), " "compressible(value) " @@ -7562,24 +7547,23 @@ nsresult PrepareDatastoreOp::DatabaseWork() { return rv; } - rv = connection->RemoveFunction(NS_LITERAL_CSTRING("compress")); + rv = connection->RemoveFunction("compress"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = connection->RemoveFunction(NS_LITERAL_CSTRING("compressible")); + rv = connection->RemoveFunction("compressible"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = connection->CreateStatement( - NS_LITERAL_CSTRING("UPDATE database SET usage = :usage;"), - getter_AddRefs(stmt)); + rv = connection->CreateStatement("UPDATE database SET usage = :usage;"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("usage"), newUsage); + rv = stmt->BindInt64ByName("usage"_ns, newUsage); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -7590,9 +7574,9 @@ nsresult PrepareDatastoreOp::DatabaseWork() { } rv = connection->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM webappsstore2 " - "WHERE originKey = :originKey " - "AND originAttributes = :originAttributes;"), + nsLiteralCString("DELETE FROM webappsstore2 " + "WHERE originKey = :originKey " + "AND originAttributes = :originAttributes;"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -7731,10 +7715,9 @@ nsresult PrepareDatastoreOp::VerifyDatabaseInformation( MOZ_ASSERT(aConnection); nsCOMPtr stmt; - nsresult rv = - aConnection->CreateStatement(NS_LITERAL_CSTRING("SELECT origin " - "FROM database"), - getter_AddRefs(stmt)); + nsresult rv = aConnection->CreateStatement(nsLiteralCString("SELECT origin " + "FROM database"), + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -8157,8 +8140,8 @@ nsresult PrepareDatastoreOp::LoadDataOp::DoDatastoreWork() { Connection::CachedStatement stmt; nsresult rv = mConnection->GetCachedStatement( - NS_LITERAL_CSTRING("SELECT key, value, utf16Length, compressed " - "FROM data;"), + nsLiteralCString("SELECT key, value, utf16Length, compressed " + "FROM data;"), &stmt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -8611,17 +8594,17 @@ void ArchivedOriginScope::GetBindingClause(nsACString& aBindingClause) const { : mBindingClause(aBindingClause) {} void operator()(const Origin& aOrigin) { - *mBindingClause = NS_LITERAL_CSTRING( + *mBindingClause = nsLiteralCString( " WHERE originKey = :originKey " "AND originAttributes = :originAttributes"); } void operator()(const Prefix& aPrefix) { - *mBindingClause = NS_LITERAL_CSTRING(" WHERE originKey = :originKey"); + *mBindingClause = " WHERE originKey = :originKey"_ns; } void operator()(const Pattern& aPattern) { - *mBindingClause = NS_LITERAL_CSTRING( + *mBindingClause = nsLiteralCString( " WHERE originAttributes MATCH :originAttributesPattern"); } @@ -8642,13 +8625,13 @@ nsresult ArchivedOriginScope::BindToStatement( explicit Matcher(mozIStorageStatement* aStmt) : mStmt(aStmt) {} nsresult operator()(const Origin& aOrigin) { - nsresult rv = mStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - aOrigin.OriginNoSuffix()); + nsresult rv = + mStmt->BindUTF8StringByName("originKey"_ns, aOrigin.OriginNoSuffix()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = mStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), + rv = mStmt->BindUTF8StringByName("originAttributes"_ns, aOrigin.OriginSuffix()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -8658,8 +8641,8 @@ nsresult ArchivedOriginScope::BindToStatement( } nsresult operator()(const Prefix& aPrefix) { - nsresult rv = mStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - aPrefix.OriginNoSuffix()); + nsresult rv = + mStmt->BindUTF8StringByName("originKey"_ns, aPrefix.OriginNoSuffix()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -8668,9 +8651,8 @@ nsresult ArchivedOriginScope::BindToStatement( } nsresult operator()(const Pattern& aPattern) { - nsresult rv = mStmt->BindUTF8StringByName( - NS_LITERAL_CSTRING("originAttributesPattern"), - NS_LITERAL_CSTRING("pattern1")); + nsresult rv = mStmt->BindUTF8StringByName("originAttributesPattern"_ns, + "pattern1"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -9176,14 +9158,14 @@ nsresult QuotaClient::AboutToClearOrigins( nsCOMPtr function( new MatchFunction(archivedOriginScope->GetPattern())); - rv = connection->CreateFunction(NS_LITERAL_CSTRING("match"), 2, function); + rv = connection->CreateFunction("match"_ns, 2, function); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } nsCOMPtr stmt; - rv = connection->CreateStatement(NS_LITERAL_CSTRING("BEGIN IMMEDIATE;"), + rv = connection->CreateStatement("BEGIN IMMEDIATE;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -9195,23 +9177,20 @@ nsresult QuotaClient::AboutToClearOrigins( } if (shadowWrites) { - rv = PerformDelete(connection, NS_LITERAL_CSTRING("main"), - archivedOriginScope.get()); + rv = PerformDelete(connection, "main"_ns, archivedOriginScope.get()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } if (hasDataForRemoval) { - rv = PerformDelete(connection, NS_LITERAL_CSTRING("archive"), - archivedOriginScope.get()); + rv = PerformDelete(connection, "archive"_ns, archivedOriginScope.get()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } - rv = connection->CreateStatement(NS_LITERAL_CSTRING("COMMIT;"), - getter_AddRefs(stmt)); + rv = connection->CreateStatement("COMMIT;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -9224,7 +9203,7 @@ nsresult QuotaClient::AboutToClearOrigins( stmt = nullptr; if (archivedOriginScope->IsPattern()) { - rv = connection->RemoveFunction(NS_LITERAL_CSTRING("match")); + rv = connection->RemoveFunction("match"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -9581,10 +9560,9 @@ nsresult QuotaClient::PerformDelete( aArchivedOriginScope->GetBindingClause(bindingClause); nsCOMPtr stmt; - rv = aConnection->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM ") + - aSchemaName + - NS_LITERAL_CSTRING(".webappsstore2") + - bindingClause + NS_LITERAL_CSTRING(";"), + rv = aConnection->CreateStatement("DELETE FROM "_ns + aSchemaName + + ".webappsstore2"_ns + bindingClause + + ";"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; diff --git a/dom/mathml/MathMLElement.cpp b/dom/mathml/MathMLElement.cpp index 97b504a230fd..e7c3135c9b83 100644 --- a/dom/mathml/MathMLElement.cpp +++ b/dom/mathml/MathMLElement.cpp @@ -42,7 +42,7 @@ static nsresult ReportLengthParseError(const nsString& aValue, Document* aDocument) { AutoTArray arg = {aValue}; return nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("MathML"), aDocument, + nsIScriptError::errorFlag, "MathML"_ns, aDocument, nsContentUtils::eMATHML_PROPERTIES, "LengthParsingError", arg); } @@ -50,7 +50,7 @@ static nsresult ReportParseErrorNoTag(const nsString& aValue, nsAtom* aAtom, Document* aDocument) { AutoTArray argv = {aValue, nsDependentAtomString(aAtom)}; return nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("MathML"), aDocument, + nsIScriptError::errorFlag, "MathML"_ns, aDocument, nsContentUtils::eMATHML_PROPERTIES, "AttributeParsingErrorNoTag", argv); } @@ -336,10 +336,9 @@ bool MathMLElement::ParseNumericValue(const nsString& aString, (aFlags & PARSE_ALLOW_UNITLESS)) { // no explicit unit, this is a number that will act as a multiplier if (!(aFlags & PARSE_SUPPRESS_WARNINGS)) { - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("MathML"), aDocument, - nsContentUtils::eMATHML_PROPERTIES, - "UnitlessValuesAreDeprecated"); + nsContentUtils::ReportToConsole( + nsIScriptError::warningFlag, "MathML"_ns, aDocument, + nsContentUtils::eMATHML_PROPERTIES, "UnitlessValuesAreDeprecated"); } if (aFlags & CONVERT_UNITLESS_TO_PERCENT) { aCSSValue.SetPercentValue(floatValue); diff --git a/dom/media/ADTSDecoder.cpp b/dom/media/ADTSDecoder.cpp index 81f1cac2f53c..40f539b79ff3 100644 --- a/dom/media/ADTSDecoder.cpp +++ b/dom/media/ADTSDecoder.cpp @@ -13,7 +13,7 @@ namespace mozilla { /* static */ bool ADTSDecoder::IsEnabled() { RefPtr platform = new PDMFactory(); - return platform->SupportsMimeType(NS_LITERAL_CSTRING("audio/mp4a-latm"), + return platform->SupportsMimeType("audio/mp4a-latm"_ns, /* DecoderDoctorDiagnostics* */ nullptr); } @@ -39,7 +39,7 @@ nsTArray> ADTSDecoder::GetTracksInfo( tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/mp4a-latm"), aType)); + "audio/mp4a-latm"_ns, aType)); return tracks; } diff --git a/dom/media/AutoplayPolicy.cpp b/dom/media/AutoplayPolicy.cpp index 54670cea0425..590d845931bc 100644 --- a/dom/media/AutoplayPolicy.cpp +++ b/dom/media/AutoplayPolicy.cpp @@ -48,12 +48,9 @@ static bool IsActivelyCapturingOrHasAPermission(nsPIDOMWindowInner* aWindow) { } auto principal = nsGlobalWindowInner::Cast(aWindow)->GetPrincipal(); - return (nsContentUtils::IsExactSitePermAllow(principal, - NS_LITERAL_CSTRING("camera")) || - nsContentUtils::IsExactSitePermAllow( - principal, NS_LITERAL_CSTRING("microphone")) || - nsContentUtils::IsExactSitePermAllow(principal, - NS_LITERAL_CSTRING("screen"))); + return (nsContentUtils::IsExactSitePermAllow(principal, "camera"_ns) || + nsContentUtils::IsExactSitePermAllow(principal, "microphone"_ns) || + nsContentUtils::IsExactSitePermAllow(principal, "screen"_ns)); } static uint32_t SiteAutoplayPerm(nsPIDOMWindowInner* aWindow) { @@ -348,8 +345,8 @@ uint32_t AutoplayPolicy::GetSiteAutoplayPermission(nsIPrincipal* aPrincipal) { } uint32_t perm = nsIPermissionManager::DENY_ACTION; - permMgr->TestExactPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("autoplay-media"), &perm); + permMgr->TestExactPermissionFromPrincipal(aPrincipal, "autoplay-media"_ns, + &perm); return perm; } diff --git a/dom/media/BackgroundVideoDecodingPermissionObserver.cpp b/dom/media/BackgroundVideoDecodingPermissionObserver.cpp index eebbbc960db6..32cbac782654 100644 --- a/dom/media/BackgroundVideoDecodingPermissionObserver.cpp +++ b/dom/media/BackgroundVideoDecodingPermissionObserver.cpp @@ -102,9 +102,9 @@ void BackgroundVideoDecodingPermissionObserver::EnableEvent() const { return; } - RefPtr asyncDispatcher = new AsyncEventDispatcher( - doc, NS_LITERAL_STRING("UnselectedTabHover:Enable"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(doc, u"UnselectedTabHover:Enable"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->PostDOMEvent(); } @@ -119,9 +119,9 @@ void BackgroundVideoDecodingPermissionObserver::DisableEvent() const { return; } - RefPtr asyncDispatcher = new AsyncEventDispatcher( - doc, NS_LITERAL_STRING("UnselectedTabHover:Disable"), CanBubble::eYes, - ChromeOnlyDispatch::eYes); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(doc, u"UnselectedTabHover:Disable"_ns, + CanBubble::eYes, ChromeOnlyDispatch::eYes); asyncDispatcher->PostDOMEvent(); } diff --git a/dom/media/Benchmark.cpp b/dom/media/Benchmark.cpp index 22a8c4cbb18b..a6192c65c9e7 100644 --- a/dom/media/Benchmark.cpp +++ b/dom/media/Benchmark.cpp @@ -104,8 +104,7 @@ bool VP9Benchmark::IsVP9DecodeFast(bool aDefault) { if (XRE_IsContentProcess()) { dom::ContentChild* contentChild = dom::ContentChild::GetSingleton(); if (contentChild) { - contentChild->SendNotifyBenchmarkResult(NS_LITERAL_STRING("VP9"), - aDecodeFps); + contentChild->SendNotifyBenchmarkResult(u"VP9"_ns, aDecodeFps); } } else { Preferences::SetUint(sBenchmarkFpsPref, aDecodeFps); diff --git a/dom/media/ChannelMediaResource.cpp b/dom/media/ChannelMediaResource.cpp index fc8f09a8a0f5..467268f5e84a 100644 --- a/dom/media/ChannelMediaResource.cpp +++ b/dom/media/ChannelMediaResource.cpp @@ -114,8 +114,7 @@ void ChannelMediaResource::Listener::Revoke() { static bool IsPayloadCompressed(nsIHttpChannel* aChannel) { nsAutoCString encoding; - Unused << aChannel->GetResponseHeader(NS_LITERAL_CSTRING("Content-Encoding"), - encoding); + Unused << aChannel->GetResponseHeader("Content-Encoding"_ns, encoding); return encoding.Length() > 0; } @@ -191,8 +190,7 @@ nsresult ChannelMediaResource::OnStartRequest(nsIRequest* aRequest, } nsAutoCString ranges; - Unused << hc->GetResponseHeader(NS_LITERAL_CSTRING("Accept-Ranges"), - ranges); + Unused << hc->GetResponseHeader("Accept-Ranges"_ns, ranges); bool acceptsRanges = net::nsHttp::FindToken(ranges.get(), "bytes", HTTP_HEADER_VALUE_SEPS); @@ -305,15 +303,14 @@ nsresult ChannelMediaResource::ParseContentRangeHeader( NS_ENSURE_ARG(aHttpChan); nsAutoCString rangeStr; - nsresult rv = aHttpChan->GetResponseHeader( - NS_LITERAL_CSTRING("Content-Range"), rangeStr); + nsresult rv = aHttpChan->GetResponseHeader("Content-Range"_ns, rangeStr); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_FALSE(rangeStr.IsEmpty(), NS_ERROR_ILLEGAL_VALUE); // Parse the range header: e.g. Content-Range: bytes 7000-7999/8000. - int32_t spacePos = rangeStr.Find(NS_LITERAL_CSTRING(" ")); - int32_t dashPos = rangeStr.Find(NS_LITERAL_CSTRING("-"), true, spacePos); - int32_t slashPos = rangeStr.Find(NS_LITERAL_CSTRING("/"), true, dashPos); + int32_t spacePos = rangeStr.Find(" "_ns); + int32_t dashPos = rangeStr.Find("-"_ns, true, spacePos); + int32_t slashPos = rangeStr.Find("/"_ns, true, dashPos); nsAutoCString aRangeStartText; rangeStr.Mid(aRangeStartText, spacePos + 1, dashPos - (spacePos + 1)); @@ -572,8 +569,7 @@ nsresult ChannelMediaResource::SetupChannelHeaders(int64_t aOffset) { nsAutoCString rangeString("bytes="); rangeString.AppendInt(aOffset); rangeString.Append('-'); - nsresult rv = - hc->SetRequestHeader(NS_LITERAL_CSTRING("Range"), rangeString, false); + nsresult rv = hc->SetRequestHeader("Range"_ns, rangeString, false); NS_ENSURE_SUCCESS(rv, rv); // Send Accept header for video and audio types only (Bug 489071) diff --git a/dom/media/DOMMediaStream.cpp b/dom/media/DOMMediaStream.cpp index b41f04ec49aa..df45945adc1e 100644 --- a/dom/media/DOMMediaStream.cpp +++ b/dom/media/DOMMediaStream.cpp @@ -395,7 +395,7 @@ void DOMMediaStream::AddTrackInternal(MediaStreamTrack* aTrack) { LOG(LogLevel::Debug, ("DOMMediaStream %p Adding owned track %p", this, aTrack)); AddTrack(*aTrack); - DispatchTrackEvent(NS_LITERAL_STRING("addtrack"), aTrack); + DispatchTrackEvent(u"addtrack"_ns, aTrack); } void DOMMediaStream::RemoveTrackInternal(MediaStreamTrack* aTrack) { @@ -405,7 +405,7 @@ void DOMMediaStream::RemoveTrackInternal(MediaStreamTrack* aTrack) { return; } RemoveTrack(*aTrack); - DispatchTrackEvent(NS_LITERAL_STRING("removetrack"), aTrack); + DispatchTrackEvent(u"removetrack"_ns, aTrack); } already_AddRefed DOMMediaStream::GetPrincipal() { diff --git a/dom/media/GVAutoplayPermissionRequest.cpp b/dom/media/GVAutoplayPermissionRequest.cpp index cc207e73fe41..df9402f3cd45 100644 --- a/dom/media/GVAutoplayPermissionRequest.cpp +++ b/dom/media/GVAutoplayPermissionRequest.cpp @@ -119,12 +119,11 @@ void GVAutoplayPermissionRequest::CreateRequest(nsGlobalWindowInner* aWindow, GVAutoplayPermissionRequest::GVAutoplayPermissionRequest( nsGlobalWindowInner* aWindow, BrowsingContext* aContext, RType aType) - : ContentPermissionRequestBase( - aWindow->GetPrincipal(), aWindow, - NS_LITERAL_CSTRING(""), // No testing pref used in this class - aType == RType::eAUDIBLE - ? NS_LITERAL_CSTRING("autoplay-media-audible") - : NS_LITERAL_CSTRING("autoplay-media-inaudible")), + : ContentPermissionRequestBase(aWindow->GetPrincipal(), aWindow, + ""_ns, // No testing pref used in this class + aType == RType::eAUDIBLE + ? "autoplay-media-audible"_ns + : "autoplay-media-inaudible"_ns), mType(aType), mContext(aContext) { MOZ_ASSERT(mContext); diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp index d74790834fe5..ebac086f05f9 100644 --- a/dom/media/GraphDriver.cpp +++ b/dom/media/GraphDriver.cpp @@ -501,8 +501,7 @@ AudioCallbackDriver::AudioCallbackDriver( mInputDeviceID(aInputDeviceID), mIterationDurationMS(MEDIA_GRAPH_TARGET_PERIOD_MS), mStarted(false), - mInitShutdownThread( - SharedThreadPool::Get(NS_LITERAL_CSTRING("CubebOperation"), 1)), + mInitShutdownThread(SharedThreadPool::Get("CubebOperation"_ns, 1)), mAudioThreadId(0), mAudioThreadIdInCb(std::thread::id()), mAudioStreamState(AudioStreamState::None), diff --git a/dom/media/MediaDecoder.cpp b/dom/media/MediaDecoder.cpp index 581a402102b8..041d3229b999 100644 --- a/dom/media/MediaDecoder.cpp +++ b/dom/media/MediaDecoder.cpp @@ -418,28 +418,24 @@ void MediaDecoder::OnPlaybackEvent(MediaPlaybackEvent&& aEvent) { Invalidate(); break; case MediaPlaybackEvent::EnterVideoSuspend: - GetOwner()->DispatchAsyncEvent(NS_LITERAL_STRING("mozentervideosuspend")); + GetOwner()->DispatchAsyncEvent(u"mozentervideosuspend"_ns); mIsVideoDecodingSuspended = true; break; case MediaPlaybackEvent::ExitVideoSuspend: - GetOwner()->DispatchAsyncEvent(NS_LITERAL_STRING("mozexitvideosuspend")); + GetOwner()->DispatchAsyncEvent(u"mozexitvideosuspend"_ns); mIsVideoDecodingSuspended = false; break; case MediaPlaybackEvent::StartVideoSuspendTimer: - GetOwner()->DispatchAsyncEvent( - NS_LITERAL_STRING("mozstartvideosuspendtimer")); + GetOwner()->DispatchAsyncEvent(u"mozstartvideosuspendtimer"_ns); break; case MediaPlaybackEvent::CancelVideoSuspendTimer: - GetOwner()->DispatchAsyncEvent( - NS_LITERAL_STRING("mozcancelvideosuspendtimer")); + GetOwner()->DispatchAsyncEvent(u"mozcancelvideosuspendtimer"_ns); break; case MediaPlaybackEvent::VideoOnlySeekBegin: - GetOwner()->DispatchAsyncEvent( - NS_LITERAL_STRING("mozvideoonlyseekbegin")); + GetOwner()->DispatchAsyncEvent(u"mozvideoonlyseekbegin"_ns); break; case MediaPlaybackEvent::VideoOnlySeekCompleted: - GetOwner()->DispatchAsyncEvent( - NS_LITERAL_STRING("mozvideoonlyseekcompleted")); + GetOwner()->DispatchAsyncEvent(u"mozvideoonlyseekcompleted"_ns); break; default: break; @@ -928,7 +924,7 @@ void MediaDecoder::DurationChanged() { // of whether we should fire durationchange on explicit infinity. if (mFiredMetadataLoaded && (!mozilla::IsInfinite(mDuration) || mExplicitDuration.isSome())) { - GetOwner()->DispatchAsyncEvent(NS_LITERAL_STRING("durationchange")); + GetOwner()->DispatchAsyncEvent(u"durationchange"_ns); } if (CurrentPosition() > TimeUnit::FromSeconds(mDuration)) { @@ -1290,10 +1286,10 @@ MediaMemoryTracker::CollectReports(nsIHandleReportCallback* aHandleReport, AbstractThread::MainThread(), __func__, [handleReport, data](size_t size) { handleReport->Callback( - EmptyCString(), NS_LITERAL_CSTRING("explicit/media/resources"), - KIND_HEAP, UNITS_BYTES, size, - NS_LITERAL_CSTRING("Memory used by media resources including " - "streaming buffers, caches, etc."), + EmptyCString(), "explicit/media/resources"_ns, KIND_HEAP, + UNITS_BYTES, size, + nsLiteralCString("Memory used by media resources including " + "streaming buffers, caches, etc."), data); nsCOMPtr imgr = diff --git a/dom/media/MediaDecoderStateMachine.cpp b/dom/media/MediaDecoderStateMachine.cpp index b776661a5d1a..f791ebf429aa 100644 --- a/dom/media/MediaDecoderStateMachine.cpp +++ b/dom/media/MediaDecoderStateMachine.cpp @@ -2165,8 +2165,8 @@ static void ReportRecoveryTelemetry(const TimeStamp& aRecoveryStart, double duration_ms = duration.ToMilliseconds(); Telemetry::Accumulate(Telemetry::VIDEO_SUSPEND_RECOVERY_TIME_MS, key, uint32_t(duration_ms + 0.5)); - Telemetry::Accumulate(Telemetry::VIDEO_SUSPEND_RECOVERY_TIME_MS, - NS_LITERAL_CSTRING("All"), uint32_t(duration_ms + 0.5)); + Telemetry::Accumulate(Telemetry::VIDEO_SUSPEND_RECOVERY_TIME_MS, "All"_ns, + uint32_t(duration_ms + 0.5)); } void MediaDecoderStateMachine::StateObject::HandleResumeVideoDecoding( diff --git a/dom/media/MediaDevices.cpp b/dom/media/MediaDevices.cpp index 35f01c4ef892..9c11913c0b89 100644 --- a/dom/media/MediaDevices.cpp +++ b/dom/media/MediaDevices.cpp @@ -201,7 +201,7 @@ void MediaDevices::OnDeviceChange() { mFuzzTimer->InitWithNamedFuncCallback( [](nsITimer*, void* aClosure) { MediaDevices* md = static_cast(aClosure); - md->DispatchTrustedEvent(NS_LITERAL_STRING("devicechange")); + md->DispatchTrustedEvent(u"devicechange"_ns); md->mFuzzTimer = nullptr; }, this, DEVICECHANGE_HOLD_TIME_IN_MS, nsITimer::TYPE_ONE_SHOT, diff --git a/dom/media/MediaFormatReader.cpp b/dom/media/MediaFormatReader.cpp index bccb29836f23..f42b28455138 100644 --- a/dom/media/MediaFormatReader.cpp +++ b/dom/media/MediaFormatReader.cpp @@ -126,7 +126,7 @@ void MediaFormatReader::DecoderData::ShutdownDecoder() { // mShutdownPromisePool will handle the order of decoder shutdown so // we can forget mDecoder and be ready to create a new one. mDecoder = nullptr; - mDescription = NS_LITERAL_CSTRING("shutdown"); + mDescription = "shutdown"_ns; mOwner->ScheduleUpdate(mType == MediaData::Type::AUDIO_DATA ? TrackType::kAudioTrack : TrackType::kVideoTrack); diff --git a/dom/media/MediaInfo.h b/dom/media/MediaInfo.h index 6b0dd8efc9ac..f9378eaef019 100644 --- a/dom/media/MediaInfo.h +++ b/dom/media/MediaInfo.h @@ -145,9 +145,8 @@ class VideoInfo : public TrackInfo { : VideoInfo(gfx::IntSize(aWidth, aHeight)) {} explicit VideoInfo(const gfx::IntSize& aSize) - : TrackInfo(kVideoTrack, NS_LITERAL_STRING("2"), - NS_LITERAL_STRING("main"), EmptyString(), EmptyString(), true, - 2), + : TrackInfo(kVideoTrack, u"2"_ns, u"main"_ns, EmptyString(), + EmptyString(), true, 2), mDisplay(aSize), mStereoMode(StereoMode::MONO), mImage(aSize), @@ -269,9 +268,8 @@ class VideoInfo : public TrackInfo { class AudioInfo : public TrackInfo { public: AudioInfo() - : TrackInfo(kAudioTrack, NS_LITERAL_STRING("1"), - NS_LITERAL_STRING("main"), EmptyString(), EmptyString(), true, - 1), + : TrackInfo(kAudioTrack, u"1"_ns, u"main"_ns, EmptyString(), + EmptyString(), true, 1), mRate(0), mChannels(0), mChannelMap(AudioConfig::ChannelLayout::UNKNOWN_MAP), diff --git a/dom/media/MediaMIMETypes.cpp b/dom/media/MediaMIMETypes.cpp index ce4cc05c6ba8..30a6791d12a8 100644 --- a/dom/media/MediaMIMETypes.cpp +++ b/dom/media/MediaMIMETypes.cpp @@ -158,7 +158,7 @@ Maybe MediaExtendedMIMEType::ComputeFractionalString( return Some(result); } - int32_t slashPos = frac.Find(NS_LITERAL_STRING("/")); + int32_t slashPos = frac.Find(u"/"_ns); if (slashPos == kNotFound) { return Nothing(); } diff --git a/dom/media/MediaManager.cpp b/dom/media/MediaManager.cpp index d8496cc76c0e..36738a1a40c4 100644 --- a/dom/media/MediaManager.cpp +++ b/dom/media/MediaManager.cpp @@ -1222,7 +1222,7 @@ class GetUserMediaStreamRunnable : public Runnable { "MediaSourceEnum::AudioCapture. This must be fixed with UX " "before shipping."); auto audioCaptureSource = MakeRefPtr( - principal, window, NS_LITERAL_STRING("Window audio capture"), + principal, window, u"Window audio capture"_ns, mtg->CreateAudioCaptureTrack(), mPeerIdentity); audioTrackSource = audioCaptureSource; RefPtr track = new dom::AudioStreamTrack( @@ -1273,8 +1273,7 @@ class GetUserMediaStreamRunnable : public Runnable { mHolder.Reject(MakeRefPtr( MediaMgrError::Name::AbortError, - sHasShutdown ? NS_LITERAL_STRING("In shutdown") - : NS_LITERAL_STRING("No stream.")), + sHasShutdown ? u"In shutdown"_ns : u"No stream."_ns), __func__); return NS_OK; } @@ -1311,11 +1310,10 @@ class GetUserMediaStreamRunnable : public Runnable { }, [] { return SourceListener::SourceListenerPromise:: - CreateAndReject( - MakeRefPtr( - MediaMgrError::Name::AbortError, - NS_LITERAL_STRING("In shutdown")), - __func__); + CreateAndReject(MakeRefPtr( + MediaMgrError::Name::AbortError, + u"In shutdown"_ns), + __func__); }); return resolvePromise; }, @@ -1574,7 +1572,7 @@ class GetUserMediaTask : public Runnable { if (errorMsg) { LOG("%s %" PRIu32, errorMsg, static_cast(rv)); if (badConstraint) { - Fail(MediaMgrError::Name::OverconstrainedError, NS_LITERAL_STRING(""), + Fail(MediaMgrError::Name::OverconstrainedError, u""_ns, NS_ConvertUTF8toUTF16(badConstraint)); } else { Fail(MediaMgrError::Name::NotReadableError, @@ -1694,7 +1692,7 @@ void MediaManager::GuessVideoDeviceGroupIDs(MediaDeviceSet& aDevices, // More than one device found, it is impossible to know which group id // is the correct one. updateGroupId = false; - newVideoGroupID = NS_LITERAL_STRING(""); + newVideoGroupID = u""_ns; break; } } @@ -2071,8 +2069,7 @@ MediaManager* MediaManager::Get() { public: Blocker() : media::ShutdownBlocker( - NS_LITERAL_STRING("Media shutdown: blocking on media thread")) { - } + u"Media shutdown: blocking on media thread"_ns) {} NS_IMETHOD BlockShutdown(nsIAsyncShutdownClient*) override { MOZ_RELEASE_ASSERT(MediaManager::GetIfExists()); @@ -2084,7 +2081,7 @@ MediaManager* MediaManager::Get() { sSingleton->mShutdownBlocker = new Blocker(); nsresult rv = media::GetShutdownBarrier()->AddBlocker( sSingleton->mShutdownBlocker, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("")); + u""_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } return sSingleton; @@ -2182,8 +2179,8 @@ nsresult MediaManager::NotifyRecordingStatusChange( NS_ConvertUTF8toUTF16 requestURL(pageURL); - props->SetPropertyAsAString(NS_LITERAL_STRING("requestURL"), requestURL); - props->SetPropertyAsInterface(NS_LITERAL_STRING("window"), aWindow); + props->SetPropertyAsAString(u"requestURL"_ns, requestURL); + props->SetPropertyAsInterface(u"window"_ns, aWindow); obs->NotifyObservers(static_cast(props), "recording-device-events", nullptr); @@ -2340,9 +2337,8 @@ RefPtr MediaManager::GetUserMedia( if (!IsOn(c.mVideo) && !IsOn(c.mAudio)) { return StreamPromise::CreateAndReject( - MakeRefPtr( - MediaMgrError::Name::TypeError, - NS_LITERAL_STRING("audio and/or video is required")), + MakeRefPtr(MediaMgrError::Name::TypeError, + u"audio and/or video is required"_ns), __func__); } @@ -2355,7 +2351,7 @@ RefPtr MediaManager::GetUserMedia( if (sHasShutdown) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::AbortError, - NS_LITERAL_STRING("In shutdown")), + u"In shutdown"_ns), __func__); } @@ -2466,8 +2462,7 @@ RefPtr MediaManager::GetUserMedia( default: { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING(""), - NS_LITERAL_STRING("mediaSource")), + u""_ns, u"mediaSource"_ns), __func__); } } @@ -2545,8 +2540,7 @@ RefPtr MediaManager::GetUserMedia( default: { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING(""), - NS_LITERAL_STRING("mediaSource")), + u""_ns, u"mediaSource"_ns), __func__); } } @@ -2584,13 +2578,11 @@ RefPtr MediaManager::GetUserMedia( if (Preferences::GetBool("media.getusermedia.microphone.deny", false)) { audioPerm = nsIPermissionManager::DENY_ACTION; } else { - rv = permDelegate->GetPermission(NS_LITERAL_CSTRING("microphone"), - &audioPerm, true); + rv = permDelegate->GetPermission("microphone"_ns, &audioPerm, true); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } else { - rv = permDelegate->GetPermission(NS_LITERAL_CSTRING("screen"), - &audioPerm, true); + rv = permDelegate->GetPermission("screen"_ns, &audioPerm, true); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } @@ -2601,13 +2593,11 @@ RefPtr MediaManager::GetUserMedia( if (Preferences::GetBool("media.getusermedia.camera.deny", false)) { videoPerm = nsIPermissionManager::DENY_ACTION; } else { - rv = permDelegate->GetPermission(NS_LITERAL_CSTRING("camera"), - &videoPerm, true); + rv = permDelegate->GetPermission("camera"_ns, &videoPerm, true); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } else { - rv = permDelegate->GetPermission(NS_LITERAL_CSTRING("screen"), - &videoPerm, true); + rv = permDelegate->GetPermission("screen"_ns, &videoPerm, true); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } @@ -2741,8 +2731,8 @@ RefPtr MediaManager::GetUserMedia( windowListener->Remove(sourceListener); return StreamPromise::CreateAndReject( MakeRefPtr( - MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING(""), constraint), + MediaMgrError::Name::OverconstrainedError, u""_ns, + constraint), __func__); } if (!devices->Length()) { @@ -2847,17 +2837,16 @@ RefPtr MediaManager::GetDisplayMedia( if (!doc->HasBeenUserGestureActivated()) { return StreamPromise::CreateAndReject( - MakeRefPtr( - MediaMgrError::Name::InvalidStateError, - NS_LITERAL_STRING( - "getDisplayMedia must be called from a user gesture handler.")), + MakeRefPtr(MediaMgrError::Name::InvalidStateError, + u"getDisplayMedia must be called from a user " + u"gesture handler."_ns), __func__); } if (!IsOn(aConstraintsPassedIn.mVideo)) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::TypeError, - NS_LITERAL_STRING("video is required")), + u"video is required"_ns), __func__); } @@ -2869,7 +2858,7 @@ RefPtr MediaManager::GetDisplayMedia( if (vc.mAdvanced.WasPassed()) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::TypeError, - NS_LITERAL_STRING("advanced not allowed")), + u"advanced not allowed"_ns), __func__); } auto getCLR = [](const auto& aCon) -> const ConstrainLongRange& { @@ -2890,13 +2879,13 @@ RefPtr MediaManager::GetDisplayMedia( if (w.mMin.WasPassed() || h.mMin.WasPassed() || f.mMin.WasPassed()) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::TypeError, - NS_LITERAL_STRING("min not allowed")), + u"min not allowed"_ns), __func__); } if (w.mExact.WasPassed() || h.mExact.WasPassed() || f.mExact.WasPassed()) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::TypeError, - NS_LITERAL_STRING("exact not allowed")), + u"exact not allowed"_ns), __func__); } // As a UA optimization, we fail early without incurring a prompt, on @@ -2915,7 +2904,7 @@ RefPtr MediaManager::GetDisplayMedia( if (badConstraint) { return StreamPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING(""), + u""_ns, NS_ConvertASCIItoUTF16(badConstraint)), __func__); } @@ -2958,8 +2947,8 @@ void MediaManager::AnonymizeDevices(MediaDeviceSet& aDevices, nsString name; device->GetName(name); - if (name.Find(NS_LITERAL_STRING("AirPods")) != -1) { - name = NS_LITERAL_STRING("AirPods"); + if (name.Find(u"AirPods"_ns) != -1) { + name = u"AirPods"_ns; } device = new MediaDevice(device, id, groupId, rawId, rawGroupId, name); } @@ -3145,7 +3134,7 @@ RefPtr MediaManager::EnumerateDevices( if (sHasShutdown) { return DevicesPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::AbortError, - NS_LITERAL_STRING("In shutdown")), + u"In shutdown"_ns), __func__); } uint64_t windowId = aWindow->WindowID(); @@ -3176,14 +3165,14 @@ RefPtr MediaManager::EnumerateDevices( // Only expose devices which are allowed to use: // https://w3c.github.io/mediacapture-main/#dom-mediadevices-enumeratedevices - MediaSourceEnum videoType = dom::FeaturePolicyUtils::IsFeatureAllowed( - doc, NS_LITERAL_STRING("camera")) - ? MediaSourceEnum::Camera - : MediaSourceEnum::Other; - MediaSourceEnum audioType = dom::FeaturePolicyUtils::IsFeatureAllowed( - doc, NS_LITERAL_STRING("microphone")) - ? MediaSourceEnum::Microphone - : MediaSourceEnum::Other; + MediaSourceEnum videoType = + dom::FeaturePolicyUtils::IsFeatureAllowed(doc, u"camera"_ns) + ? MediaSourceEnum::Camera + : MediaSourceEnum::Other; + MediaSourceEnum audioType = + dom::FeaturePolicyUtils::IsFeatureAllowed(doc, u"microphone"_ns) + ? MediaSourceEnum::Microphone + : MediaSourceEnum::Other; auto devices = MakeRefPtr(); MediaSinkEnum audioOutputType = MediaSinkEnum::Other; @@ -3812,8 +3801,7 @@ nsresult MediaManager::Observe(nsISupports* aSubject, const char* aTopic, } if (sHasShutdown) { - return task->Denied(MediaMgrError::Name::AbortError, - NS_LITERAL_STRING("In shutdown")); + return task->Denied(MediaMgrError::Name::AbortError, u"In shutdown"_ns); } // Reuse the same thread to save memory. MediaManager::PostTask(task.forget()); @@ -4072,13 +4060,11 @@ bool MediaManager::IsActivelyCapturingOrHasAPermission(uint64_t aWindowId) { uint32_t audio = nsIPermissionManager::UNKNOWN_ACTION; uint32_t video = nsIPermissionManager::UNKNOWN_ACTION; { - rv = permDelegate->GetPermission(NS_LITERAL_CSTRING("microphone"), &audio, - true); + rv = permDelegate->GetPermission("microphone"_ns, &audio, true); if (NS_WARN_IF(NS_FAILED(rv))) { return false; } - rv = - permDelegate->GetPermission(NS_LITERAL_CSTRING("camera"), &video, true); + rv = permDelegate->GetPermission("camera"_ns, &video, true); if (NS_WARN_IF(NS_FAILED(rv))) { return false; } @@ -4656,11 +4642,10 @@ SourceListener::ApplyConstraintsToTrack( static_cast(rv)); } - aHolder.Reject( - MakeRefPtr( - MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING(""), NS_ConvertASCIItoUTF16(badConstraint)), - __func__); + aHolder.Reject(MakeRefPtr( + MediaMgrError::Name::OverconstrainedError, u""_ns, + NS_ConvertASCIItoUTF16(badConstraint)), + __func__); return; } // Reconfigure was successful diff --git a/dom/media/MediaManager.h b/dom/media/MediaManager.h index d8710443d330..d4b6e52c4339 100644 --- a/dom/media/MediaManager.h +++ b/dom/media/MediaManager.h @@ -72,7 +72,7 @@ class MediaDevice : public nsIMediaDevice { MediaDevice(const RefPtr& aAudioDeviceInfo, const nsString& aID, const nsString& aGroupID, - const nsString& aRawID = NS_LITERAL_STRING("")); + const nsString& aRawID = u""_ns); MediaDevice(const RefPtr& aOther, const nsString& aID, const nsString& aGroupID, const nsString& aRawID, diff --git a/dom/media/MediaRecorder.cpp b/dom/media/MediaRecorder.cpp index 01abf17e4f82..314157dffc02 100644 --- a/dom/media/MediaRecorder.cpp +++ b/dom/media/MediaRecorder.cpp @@ -115,9 +115,8 @@ class MediaRecorderReporter final : public nsIMemoryReporter { } handleReport->Callback( - EmptyCString(), NS_LITERAL_CSTRING("explicit/media/recorder"), - KIND_HEAP, UNITS_BYTES, sum, - NS_LITERAL_CSTRING("Memory used by media recorder."), data); + EmptyCString(), "explicit/media/recorder"_ns, KIND_HEAP, + UNITS_BYTES, sum, "Memory used by media recorder."_ns, data); manager->EndReport(); }, @@ -230,9 +229,9 @@ nsCString TypeSupportToCString(TypeSupport aSupport, "Video cannot be recorded with %s as it is an audio type", mime.get()); case TypeSupport::ContainersDisabled: - return NS_LITERAL_CSTRING("All containers are disabled"); + return "All containers are disabled"_ns; case TypeSupport::CodecsDisabled: - return NS_LITERAL_CSTRING("All codecs are disabled"); + return "All codecs are disabled"_ns; case TypeSupport::ContainerUnsupported: return nsPrintfCString("%s indicates an unsupported container", mime.get()); @@ -243,7 +242,7 @@ nsCString TypeSupportToCString(TypeSupport aSupport, mime.get()); default: MOZ_ASSERT_UNREACHABLE("Unknown TypeSupport"); - return NS_LITERAL_CSTRING("Unknown error"); + return "Unknown error"_ns; } } @@ -476,20 +475,20 @@ nsString SelectMimeType(bool aHasVideo, bool aHasAudio, // order to be valid. Use them as is. majorType = constrainedType->Type().AsString(); } else if (aHasVideo) { - majorType = NS_LITERAL_CSTRING(VIDEO_WEBM); + majorType = nsLiteralCString(VIDEO_WEBM); } else { - majorType = NS_LITERAL_CSTRING(AUDIO_OGG); + majorType = nsLiteralCString(AUDIO_OGG); } } nsCString codecs; { if (aHasVideo && aHasAudio) { - codecs = NS_LITERAL_CSTRING("\"vp8, opus\""); + codecs = "\"vp8, opus\""_ns; } else if (aHasVideo) { - codecs = NS_LITERAL_CSTRING("vp8"); + codecs = "vp8"_ns; } else { - codecs = NS_LITERAL_CSTRING("opus"); + codecs = "opus"_ns; } } result = NS_ConvertUTF8toUTF16( @@ -753,8 +752,8 @@ class MediaRecorder::Session : public PrincipalChangeObserver, // check track principals async later. nsPIDOMWindowInner* window = mRecorder->GetOwner(); Document* document = window ? window->GetExtantDoc() : nullptr; - nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Media"), document, + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "Media"_ns, + document, nsContentUtils::eDOM_PROPERTIES, "MediaRecorderMultiTracksNotSupported"); DoSessionEndTask(NS_ERROR_ABORT); @@ -1065,7 +1064,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, mShutdownBlocker = MakeAndAddRef(this, name); nsresult rv = GetShutdownBarrier()->AddBlocker( mShutdownBlocker, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("MediaRecorder::Session: shutdown")); + u"MediaRecorder::Session: shutdown"_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); mEncoder = MediaEncoder::CreateEncoder( @@ -1151,7 +1150,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, } if (needsStartEvent) { - mRecorder->DispatchSimpleEvent(NS_LITERAL_STRING("start")); + mRecorder->DispatchSimpleEvent(u"start"_ns); } // If there was an error, Fire the appropriate one @@ -1181,7 +1180,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, } // Fire an event named stop - mRecorder->DispatchSimpleEvent(NS_LITERAL_STRING("stop")); + mRecorder->DispatchSimpleEvent(u"stop"_ns); // And finally, Shutdown and destroy the Session return Shutdown(); @@ -1217,7 +1216,7 @@ class MediaRecorder::Session : public PrincipalChangeObserver, mRecorder->mMimeType = mMimeType; } - mRecorder->DispatchSimpleEvent(NS_LITERAL_STRING("start")); + mRecorder->DispatchSimpleEvent(u"start"_ns); } return NS_OK; })); @@ -1631,7 +1630,7 @@ void MediaRecorder::Pause(ErrorResult& aResult) { "MediaRecorder::Pause", [recorder = RefPtr(this)] { // 2. Let target be the MediaRecorder context object. Fire an event // named pause at target. - recorder->DispatchSimpleEvent(NS_LITERAL_STRING("pause")); + recorder->DispatchSimpleEvent(u"pause"_ns); })); // 4. return undefined. @@ -1669,7 +1668,7 @@ void MediaRecorder::Resume(ErrorResult& aResult) { "MediaRecorder::Resume", [recorder = RefPtr(this)] { // 2. Let target be the MediaRecorder context object. Fire an event // named resume at target. - recorder->DispatchSimpleEvent(NS_LITERAL_STRING("resume")); + recorder->DispatchSimpleEvent(u"resume"_ns); })); // 4. return undefined. @@ -1923,7 +1922,7 @@ nsresult MediaRecorder::CreateAndDispatchBlobEvent(BlobImpl* aBlobImpl) { init.mData = blob; RefPtr event = - BlobEvent::Constructor(this, NS_LITERAL_STRING("dataavailable"), init); + BlobEvent::Constructor(this, u"dataavailable"_ns, init); event->SetTrusted(true); ErrorResult rv; DispatchEvent(*event, rv); @@ -1979,8 +1978,8 @@ void MediaRecorder::NotifyError(nsresult aRv) { init.mError = std::move(mUnknownDomException); } - RefPtr event = MediaRecorderErrorEvent::Constructor( - this, NS_LITERAL_STRING("error"), init); + RefPtr event = + MediaRecorderErrorEvent::Constructor(this, u"error"_ns, init); event->SetTrusted(true); IgnoredErrorResult res; diff --git a/dom/media/MediaShutdownManager.cpp b/dom/media/MediaShutdownManager.cpp index 1bb764d72f9a..054f744adbf2 100644 --- a/dom/media/MediaShutdownManager.cpp +++ b/dom/media/MediaShutdownManager.cpp @@ -73,7 +73,7 @@ void MediaShutdownManager::InitStatics() { nsresult rv = GetShutdownBarrier()->AddBlocker( sInstance, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("MediaShutdownManager shutdown")); + u"MediaShutdownManager shutdown"_ns); if (NS_FAILED(rv)) { LOGW("Failed to add shutdown blocker! rv=%x", uint32_t(rv)); sInitPhase = InitFailed; @@ -124,7 +124,7 @@ void MediaShutdownManager::Unregister(MediaDecoder* aDecoder) { NS_IMETHODIMP MediaShutdownManager::GetName(nsAString& aName) { - aName = NS_LITERAL_STRING("MediaShutdownManager: shutdown"); + aName = u"MediaShutdownManager: shutdown"_ns; return NS_OK; } diff --git a/dom/media/MediaStreamTrack.cpp b/dom/media/MediaStreamTrack.cpp index 4a423b846cc7..698863b981f2 100644 --- a/dom/media/MediaStreamTrack.cpp +++ b/dom/media/MediaStreamTrack.cpp @@ -52,7 +52,7 @@ auto MediaStreamTrackSource::ApplyConstraints( -> RefPtr { return ApplyConstraintsPromise::CreateAndReject( MakeRefPtr(MediaMgrError::Name::OverconstrainedError, - NS_LITERAL_STRING("")), + u""_ns), __func__); } @@ -459,8 +459,7 @@ void MediaStreamTrack::MutedChanged(bool aNewState) { ("MediaStreamTrack %p became %s", this, aNewState ? "muted" : "unmuted")); mMuted = aNewState; - nsString eventName = - aNewState ? NS_LITERAL_STRING("mute") : NS_LITERAL_STRING("unmute"); + nsString eventName = aNewState ? u"mute"_ns : u"unmute"_ns; DispatchTrustedEvent(eventName); } @@ -573,7 +572,7 @@ void MediaStreamTrack::OverrideEnded() { NotifyEnded(); - DispatchTrustedEvent(NS_LITERAL_STRING("ended")); + DispatchTrustedEvent(u"ended"_ns); } void MediaStreamTrack::AddListener(MediaTrackListener* aListener) { diff --git a/dom/media/MediaTimer.cpp b/dom/media/MediaTimer.cpp index dc14129e6bbb..0d999de07238 100644 --- a/dom/media/MediaTimer.cpp +++ b/dom/media/MediaTimer.cpp @@ -26,7 +26,7 @@ MediaTimer::MediaTimer(bool aFuzzy) // Use the SharedThreadPool to create an nsIThreadPool with a maximum of one // thread, which is equivalent to an nsIThread for our purposes. RefPtr threadPool( - SharedThreadPool::Get(NS_LITERAL_CSTRING("MediaTimer"), 1)); + SharedThreadPool::Get("MediaTimer"_ns, 1)); mThread = threadPool.get(); mTimer = NS_NewTimer(mThread); } diff --git a/dom/media/MediaTrackGraph.cpp b/dom/media/MediaTrackGraph.cpp index 8efa9728242c..325816cb34e3 100644 --- a/dom/media/MediaTrackGraph.cpp +++ b/dom/media/MediaTrackGraph.cpp @@ -1519,7 +1519,7 @@ void MediaTrackGraphImpl::AddShutdownBlocker() { mShutdownBlocker = MakeAndAddRef(this, blockerName); nsresult rv = media::GetShutdownBarrier()->AddBlocker( mShutdownBlocker, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("MediaTrackGraph shutdown")); + u"MediaTrackGraph shutdown"_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } @@ -3261,7 +3261,7 @@ void MediaTrackGraphImpl::FinishCollectReports( #define REPORT(_path, _amount, _desc) \ aHandleReport->Callback(EmptyCString(), _path, KIND_HEAP, UNITS_BYTES, \ - _amount, NS_LITERAL_CSTRING(_desc), aData); + _amount, nsLiteralCString(_desc), aData); for (size_t i = 0; i < aAudioTrackSizes.Length(); i++) { const AudioNodeSizes& usage = aAudioTrackSizes[i]; @@ -3281,7 +3281,7 @@ void MediaTrackGraphImpl::FinishCollectReports( size_t hrtfLoaders = WebCore::HRTFDatabaseLoader::sizeOfLoaders(MallocSizeOf); if (hrtfLoaders) { - REPORT(NS_LITERAL_CSTRING( + REPORT(nsLiteralCString( "explicit/webaudio/audio-node/PannerNode/hrtf-databases"), hrtfLoaders, "Memory used by PannerNode databases (Web Audio)."); } diff --git a/dom/media/MediaTrackList.cpp b/dom/media/MediaTrackList.cpp index fa6f1ef40304..92a2d2a5a360 100644 --- a/dom/media/MediaTrackList.cpp +++ b/dom/media/MediaTrackList.cpp @@ -56,7 +56,7 @@ void MediaTrackList::AddTrack(MediaTrack* aTrack) { "Where is this track from?"); mTracks.AppendElement(aTrack); aTrack->SetTrackList(this); - CreateAndDispatchTrackEventRunner(aTrack, NS_LITERAL_STRING("addtrack")); + CreateAndDispatchTrackEventRunner(aTrack, u"addtrack"_ns); if ((!aTrack->AsAudioTrack() || !aTrack->AsAudioTrack()->Enabled()) && (!aTrack->AsVideoTrack() || !aTrack->AsVideoTrack()->Selected())) { @@ -73,7 +73,7 @@ void MediaTrackList::RemoveTrack(const RefPtr& aTrack) { mTracks.RemoveElement(aTrack); aTrack->SetEnabledInternal(false, MediaTrack::FIRE_NO_EVENTS); aTrack->SetTrackList(nullptr); - CreateAndDispatchTrackEventRunner(aTrack, NS_LITERAL_STRING("removetrack")); + CreateAndDispatchTrackEventRunner(aTrack, u"removetrack"_ns); } void MediaTrackList::RemoveTracks() { @@ -110,8 +110,8 @@ void MediaTrackList::EmptyTracks() { } void MediaTrackList::CreateAndDispatchChangeEvent() { - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("change"), CanBubble::eNo); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"change"_ns, CanBubble::eNo); asyncDispatcher->PostDOMEvent(); } diff --git a/dom/media/TextTrackList.cpp b/dom/media/TextTrackList.cpp index a67cd98226ee..ed39355085b0 100644 --- a/dom/media/TextTrackList.cpp +++ b/dom/media/TextTrackList.cpp @@ -83,7 +83,7 @@ void TextTrackList::AddTextTrack(TextTrack* aTextTrack, } mTextTracks.InsertElementSorted(aTextTrack, aCompareTT); aTextTrack->SetTextTrackList(this); - CreateAndDispatchTrackEventRunner(aTextTrack, NS_LITERAL_STRING("addtrack")); + CreateAndDispatchTrackEventRunner(aTextTrack, u"addtrack"_ns); } TextTrack* TextTrackList::GetTrackById(const nsAString& aId) { @@ -99,7 +99,7 @@ TextTrack* TextTrackList::GetTrackById(const nsAString& aId) { void TextTrackList::RemoveTextTrack(TextTrack* aTrack) { if (mTextTracks.RemoveElement(aTrack)) { - CreateAndDispatchTrackEventRunner(aTrack, NS_LITERAL_STRING("removetrack")); + CreateAndDispatchTrackEventRunner(aTrack, u"removetrack"_ns); } } @@ -129,7 +129,7 @@ void TextTrackList::CreateAndDispatchChangeEvent() { RefPtr event = NS_NewDOMEvent(this, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("change"), false, false); + event->InitEvent(u"change"_ns, false, false); event->SetTrusted(true); nsCOMPtr eventRunner = new TrackEventRunner(this, event); diff --git a/dom/media/VideoUtils.h b/dom/media/VideoUtils.h index e19a1a54b6c8..992c29a214bb 100644 --- a/dom/media/VideoUtils.h +++ b/dom/media/VideoUtils.h @@ -542,7 +542,7 @@ static bool StringListContains(const ListString& aList, inline void AppendStringIfNotEmpty(nsACString& aDest, nsACString&& aSrc) { if (!aSrc.IsEmpty()) { - aDest.Append(NS_LITERAL_CSTRING("\n")); + aDest.Append("\n"_ns); aDest.Append(aSrc); } } diff --git a/dom/media/WebVTTListener.cpp b/dom/media/WebVTTListener.cpp index c7058f7d4126..a3f3c5e8f3b4 100644 --- a/dom/media/WebVTTListener.cpp +++ b/dom/media/WebVTTListener.cpp @@ -93,7 +93,7 @@ WebVTTListener::OnStartRequest(nsIRequest* aRequest) { } LOG("OnStartRequest"); - mElement->DispatchTestEvent(NS_LITERAL_STRING("mozStartedLoadingTextTrack")); + mElement->DispatchTestEvent(u"mozStartedLoadingTextTrack"_ns); return NS_OK; } diff --git a/dom/media/doctor/DecoderDoctorDiagnostics.cpp b/dom/media/doctor/DecoderDoctorDiagnostics.cpp index cdbb5cc93228..6fccc73ffd40 100644 --- a/dom/media/doctor/DecoderDoctorDiagnostics.cpp +++ b/dom/media/doctor/DecoderDoctorDiagnostics.cpp @@ -364,9 +364,9 @@ static void ReportToConsole(dom::Document* aDocument, ? "" : NS_ConvertUTF16toUTF8(aParams[0]).get(), aParams.Length() < 2 ? "" : ", ..."); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Media"), aDocument, - nsContentUtils::eDOM_PROPERTIES, aConsoleStringId, aParams); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Media"_ns, + aDocument, nsContentUtils::eDOM_PROPERTIES, + aConsoleStringId, aParams); } static bool AllowNotification( @@ -410,13 +410,13 @@ static bool AllowDecodeIssue(const MediaResult& aDecodeIssue, return StringListContains(filter, decodeIssueName); } -static void ReportAnalysis( - dom::Document* aDocument, - const NotificationAndReportStringId& aNotification, bool aIsSolved, - const nsAString& aFormats = NS_LITERAL_STRING(""), - const MediaResult& aDecodeIssue = NS_OK, bool aDecodeIssueIsError = true, - const nsACString& aDocURL = NS_LITERAL_CSTRING(""), - const nsAString& aResourceURL = NS_LITERAL_STRING("")) { +static void ReportAnalysis(dom::Document* aDocument, + const NotificationAndReportStringId& aNotification, + bool aIsSolved, const nsAString& aFormats = u""_ns, + const MediaResult& aDecodeIssue = NS_OK, + bool aDecodeIssueIsError = true, + const nsACString& aDocURL = ""_ns, + const nsAString& aResourceURL = u""_ns) { MOZ_ASSERT(NS_IsMainThread()); if (!aDocument) { @@ -478,7 +478,7 @@ static nsString CleanItemForFormatsList(const nsAString& aItem) { static void AppendToFormatsList(nsAString& aList, const nsAString& aItem) { if (!aList.IsEmpty()) { - aList += NS_LITERAL_STRING(", "); + aList += u", "_ns; } aList += CleanItemForFormatsList(aItem); } @@ -728,7 +728,7 @@ void DecoderDoctorDocumentWatcher::SynthesizeAnalysis() { "DecoderDoctorDocumentWatcher[%p, doc=%p]::SynthesizeAnalysis() - " "Decode error: %s", this, mDocument, firstDecodeError->Description().get()); - ReportAnalysis(mDocument, sMediaDecodeError, false, NS_LITERAL_STRING(""), + ReportAnalysis(mDocument, sMediaDecodeError, false, u""_ns, *firstDecodeError, true, // aDecodeIssueIsError=true mDocument->GetDocumentURI()->GetSpecOrDefault(), @@ -741,7 +741,7 @@ void DecoderDoctorDocumentWatcher::SynthesizeAnalysis() { "DecoderDoctorDocumentWatcher[%p, doc=%p]::SynthesizeAnalysis() - " "Decode warning: %s", this, mDocument, firstDecodeWarning->Description().get()); - ReportAnalysis(mDocument, sMediaDecodeWarning, false, NS_LITERAL_STRING(""), + ReportAnalysis(mDocument, sMediaDecodeWarning, false, u""_ns, *firstDecodeWarning, false, // aDecodeIssueIsError=false mDocument->GetDocumentURI()->GetSpecOrDefault(), @@ -970,15 +970,13 @@ void DecoderDoctorDiagnostics::StoreEvent(dom::Document* aDocument, "DecoderDoctorDocumentWatcher[%p, doc=%p]::AddDiagnostics() - " "unable to initialize PulseAudio", this, aDocument); - ReportAnalysis(aDocument, sCannotInitializePulseAudio, false, - NS_LITERAL_STRING("*")); + ReportAnalysis(aDocument, sCannotInitializePulseAudio, false, u"*"_ns); } else if (aEvent.mResult == NS_OK) { DD_INFO( "DecoderDoctorDocumentWatcher[%p, doc=%p]::AddDiagnostics() - now " "able to initialize PulseAudio", this, aDocument); - ReportAnalysis(aDocument, sCannotInitializePulseAudio, true, - NS_LITERAL_STRING("*")); + ReportAnalysis(aDocument, sCannotInitializePulseAudio, true, u"*"_ns); } break; } diff --git a/dom/media/eme/EMEUtils.cpp b/dom/media/eme/EMEUtils.cpp index 13e5b24805d9..78b28f2e77c6 100644 --- a/dom/media/eme/EMEUtils.cpp +++ b/dom/media/eme/EMEUtils.cpp @@ -61,10 +61,10 @@ bool IsWidevineKeySystem(const nsAString& aKeySystem) { nsString KeySystemToGMPName(const nsAString& aKeySystem) { if (IsClearkeyKeySystem(aKeySystem)) { - return NS_LITERAL_STRING("gmp-clearkey"); + return u"gmp-clearkey"_ns; } if (IsWidevineKeySystem(aKeySystem)) { - return NS_LITERAL_STRING("gmp-widevinecdm"); + return u"gmp-widevinecdm"_ns; } MOZ_ASSERT(false, "We should only call this for known GMPs"); return EmptyString(); diff --git a/dom/media/eme/MediaEncryptedEvent.cpp b/dom/media/eme/MediaEncryptedEvent.cpp index d1fecc512682..6699d0f96a00 100644 --- a/dom/media/eme/MediaEncryptedEvent.cpp +++ b/dom/media/eme/MediaEncryptedEvent.cpp @@ -53,7 +53,7 @@ JSObject* MediaEncryptedEvent::WrapObjectInternal( already_AddRefed MediaEncryptedEvent::Constructor( EventTarget* aOwner) { RefPtr e = new MediaEncryptedEvent(aOwner); - e->InitEvent(NS_LITERAL_STRING("encrypted"), CanBubble::eNo, Cancelable::eNo); + e->InitEvent(u"encrypted"_ns, CanBubble::eNo, Cancelable::eNo); e->SetTrusted(true); return e.forget(); } @@ -62,7 +62,7 @@ already_AddRefed MediaEncryptedEvent::Constructor( EventTarget* aOwner, const nsAString& aInitDataType, const nsTArray& aInitData) { RefPtr e = new MediaEncryptedEvent(aOwner); - e->InitEvent(NS_LITERAL_STRING("encrypted"), CanBubble::eNo, Cancelable::eNo); + e->InitEvent(u"encrypted"_ns, CanBubble::eNo, Cancelable::eNo); e->mInitDataType = aInitDataType; e->mRawInitData = aInitData.Clone(); e->SetTrusted(true); diff --git a/dom/media/eme/MediaKeyError.cpp b/dom/media/eme/MediaKeyError.cpp index b2f43b050e46..8dce8d52bfaf 100644 --- a/dom/media/eme/MediaKeyError.cpp +++ b/dom/media/eme/MediaKeyError.cpp @@ -13,7 +13,7 @@ namespace dom { MediaKeyError::MediaKeyError(EventTarget* aOwner, uint32_t aSystemCode) : Event(aOwner, nullptr, nullptr), mSystemCode(aSystemCode) { - InitEvent(NS_LITERAL_STRING("error"), CanBubble::eNo, Cancelable::eNo); + InitEvent(u"error"_ns, CanBubble::eNo, Cancelable::eNo); } MediaKeyError::~MediaKeyError() = default; diff --git a/dom/media/eme/MediaKeyMessageEvent.cpp b/dom/media/eme/MediaKeyMessageEvent.cpp index 2991a8ed4960..c1788bc3bf5a 100644 --- a/dom/media/eme/MediaKeyMessageEvent.cpp +++ b/dom/media/eme/MediaKeyMessageEvent.cpp @@ -63,7 +63,7 @@ already_AddRefed MediaKeyMessageEvent::Constructor( EventTarget* aOwner, MediaKeyMessageType aMessageType, const nsTArray& aMessage) { RefPtr e = new MediaKeyMessageEvent(aOwner); - e->InitEvent(NS_LITERAL_STRING("message"), false, false); + e->InitEvent(u"message"_ns, false, false); e->mMessageType = aMessageType; e->mRawMessage = aMessage.Clone(); e->SetTrusted(true); diff --git a/dom/media/eme/MediaKeySession.cpp b/dom/media/eme/MediaKeySession.cpp index 38ec8abb1a1e..42a09c3c8d0b 100644 --- a/dom/media/eme/MediaKeySession.cpp +++ b/dom/media/eme/MediaKeySession.cpp @@ -69,7 +69,7 @@ MediaKeySession::MediaKeySession(nsPIDOMWindowInner* aParent, MediaKeys* aKeys, if (aRv.Failed()) { return; } - mClosed = MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeys.createSession")); + mClosed = MakePromise(aRv, "MediaKeys.createSession"_ns); } void MediaKeySession::SetSessionId(const nsAString& aSessionId) { @@ -196,7 +196,7 @@ already_AddRefed MediaKeySession::GenerateRequest( const nsAString& aInitDataType, const ArrayBufferViewOrArrayBuffer& aInitData, ErrorResult& aRv) { RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.generateRequest"))); + MakePromise(aRv, "MediaKeySession.generateRequest"_ns)); if (aRv.Failed()) { return nullptr; } @@ -311,8 +311,7 @@ already_AddRefed MediaKeySession::GenerateRequest( already_AddRefed MediaKeySession::Load(const nsAString& aSessionId, ErrorResult& aRv) { - RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.load"))); + RefPtr promise(MakePromise(aRv, "MediaKeySession.load"_ns)); if (aRv.Failed()) { return nullptr; } @@ -387,7 +386,7 @@ already_AddRefed MediaKeySession::Load(const nsAString& aSessionId, already_AddRefed MediaKeySession::Update( const ArrayBufferViewOrArrayBuffer& aResponse, ErrorResult& aRv) { RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.update"))); + MakePromise(aRv, "MediaKeySession.update"_ns)); if (aRv.Failed()) { return nullptr; } @@ -439,8 +438,7 @@ already_AddRefed MediaKeySession::Update( } already_AddRefed MediaKeySession::Close(ErrorResult& aRv) { - RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.close"))); + RefPtr promise(MakePromise(aRv, "MediaKeySession.close"_ns)); if (aRv.Failed()) { return nullptr; } @@ -501,7 +499,7 @@ bool MediaKeySession::IsClosed() const { return mIsClosed; } already_AddRefed MediaKeySession::Remove(ErrorResult& aRv) { RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeySession.remove"))); + MakePromise(aRv, "MediaKeySession.remove"_ns)); if (aRv.Failed()) { return nullptr; } @@ -573,8 +571,8 @@ void MediaKeySession::DispatchKeyStatusesChange() { UpdateKeyStatusMap(); - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("keystatuseschange"), CanBubble::eNo); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"keystatuseschange"_ns, CanBubble::eNo); asyncDispatcher->PostDOMEvent(); } diff --git a/dom/media/eme/MediaKeySystemAccess.cpp b/dom/media/eme/MediaKeySystemAccess.cpp index e3eab24ee026..37f59caf804c 100644 --- a/dom/media/eme/MediaKeySystemAccess.cpp +++ b/dom/media/eme/MediaKeySystemAccess.cpp @@ -85,7 +85,7 @@ already_AddRefed MediaKeySystemAccess::CreateMediaKeys( } static bool HavePluginForKeySystem(const nsCString& aKeySystem) { - nsCString api = NS_LITERAL_CSTRING(CHROMIUM_CDM_API); + nsCString api = nsLiteralCString(CHROMIUM_CDM_API); bool havePlugin = HaveGMPFor(api, {aKeySystem}); #ifdef MOZ_WIDGET_ANDROID @@ -100,7 +100,7 @@ static bool HavePluginForKeySystem(const nsCString& aKeySystem) { static MediaKeySystemStatus EnsureCDMInstalled(const nsAString& aKeySystem, nsACString& aOutMessage) { if (!HavePluginForKeySystem(NS_ConvertUTF16toUTF8(aKeySystem))) { - aOutMessage = NS_LITERAL_CSTRING("CDM is not installed"); + aOutMessage = "CDM is not installed"_ns; return MediaKeySystemStatus::Cdm_not_installed; } @@ -120,7 +120,7 @@ MediaKeySystemStatus MediaKeySystemAccess::GetKeySystemStatus( if (IsWidevineKeySystem(aKeySystem)) { if (Preferences::GetBool("media.gmp-widevinecdm.visible", false)) { if (!Preferences::GetBool("media.gmp-widevinecdm.enabled", false)) { - aOutMessage = NS_LITERAL_CSTRING("Widevine EME disabled"); + aOutMessage = "Widevine EME disabled"_ns; return MediaKeySystemStatus::Cdm_disabled; } return EnsureCDMInstalled(aKeySystem, aOutMessage); @@ -131,7 +131,7 @@ MediaKeySystemStatus MediaKeySystemAccess::GetKeySystemStatus( bool supported = mozilla::java::MediaDrmProxy::IsSchemeSupported(keySystem); if (!supported) { - aOutMessage = NS_LITERAL_CSTRING( + aOutMessage = nsLiteralCString( "KeySystem or Minimum API level not met for Widevine EME"); return MediaKeySystemStatus::Cdm_not_supported; } @@ -242,17 +242,17 @@ static nsTArray GetSupportedKeySystems() { nsTArray keySystemConfigs; { - const nsCString keySystem = NS_LITERAL_CSTRING(EME_KEY_SYSTEM_CLEARKEY); + const nsCString keySystem = nsLiteralCString(EME_KEY_SYSTEM_CLEARKEY); if (HavePluginForKeySystem(keySystem)) { KeySystemConfig clearkey; clearkey.mKeySystem.AssignLiteral(EME_KEY_SYSTEM_CLEARKEY); - clearkey.mInitDataTypes.AppendElement(NS_LITERAL_STRING("cenc")); - clearkey.mInitDataTypes.AppendElement(NS_LITERAL_STRING("keyids")); - clearkey.mInitDataTypes.AppendElement(NS_LITERAL_STRING("webm")); + clearkey.mInitDataTypes.AppendElement(u"cenc"_ns); + clearkey.mInitDataTypes.AppendElement(u"keyids"_ns); + clearkey.mInitDataTypes.AppendElement(u"webm"_ns); clearkey.mPersistentState = KeySystemFeatureSupport::Requestable; clearkey.mDistinctiveIdentifier = KeySystemFeatureSupport::Prohibited; clearkey.mSessionTypes.AppendElement(MediaKeySessionType::Temporary); - clearkey.mEncryptionSchemes.AppendElement(NS_LITERAL_STRING("cenc")); + clearkey.mEncryptionSchemes.AppendElement(u"cenc"_ns); // We do not have support for cbcs in clearkey yet. See bug 1516673. if (StaticPrefs::media_clearkey_persistent_license_enabled()) { clearkey.mSessionTypes.AppendElement( @@ -280,13 +280,13 @@ static nsTArray GetSupportedKeySystems() { } } { - const nsCString keySystem = NS_LITERAL_CSTRING(EME_KEY_SYSTEM_WIDEVINE); + const nsCString keySystem = nsLiteralCString(EME_KEY_SYSTEM_WIDEVINE); if (HavePluginForKeySystem(keySystem)) { KeySystemConfig widevine; widevine.mKeySystem.AssignLiteral(EME_KEY_SYSTEM_WIDEVINE); - widevine.mInitDataTypes.AppendElement(NS_LITERAL_STRING("cenc")); - widevine.mInitDataTypes.AppendElement(NS_LITERAL_STRING("keyids")); - widevine.mInitDataTypes.AppendElement(NS_LITERAL_STRING("webm")); + widevine.mInitDataTypes.AppendElement(u"cenc"_ns); + widevine.mInitDataTypes.AppendElement(u"keyids"_ns); + widevine.mInitDataTypes.AppendElement(u"webm"_ns); widevine.mPersistentState = KeySystemFeatureSupport::Requestable; widevine.mDistinctiveIdentifier = KeySystemFeatureSupport::Prohibited; widevine.mSessionTypes.AppendElement(MediaKeySessionType::Temporary); @@ -294,14 +294,11 @@ static nsTArray GetSupportedKeySystems() { widevine.mSessionTypes.AppendElement( MediaKeySessionType::Persistent_license); #endif - widevine.mAudioRobustness.AppendElement( - NS_LITERAL_STRING("SW_SECURE_CRYPTO")); - widevine.mVideoRobustness.AppendElement( - NS_LITERAL_STRING("SW_SECURE_CRYPTO")); - widevine.mVideoRobustness.AppendElement( - NS_LITERAL_STRING("SW_SECURE_DECODE")); - widevine.mEncryptionSchemes.AppendElement(NS_LITERAL_STRING("cenc")); - widevine.mEncryptionSchemes.AppendElement(NS_LITERAL_STRING("cbcs")); + widevine.mAudioRobustness.AppendElement(u"SW_SECURE_CRYPTO"_ns); + widevine.mVideoRobustness.AppendElement(u"SW_SECURE_CRYPTO"_ns); + widevine.mVideoRobustness.AppendElement(u"SW_SECURE_DECODE"_ns); + widevine.mEncryptionSchemes.AppendElement(u"cenc"_ns); + widevine.mEncryptionSchemes.AppendElement(u"cbcs"_ns); #if defined(MOZ_WIDGET_ANDROID) // MediaDrm.isCryptoSchemeSupported only allows passing diff --git a/dom/media/eme/MediaKeySystemAccessManager.cpp b/dom/media/eme/MediaKeySystemAccessManager.cpp index ecf4dd4ff0ab..42a9c2828310 100644 --- a/dom/media/eme/MediaKeySystemAccessManager.cpp +++ b/dom/media/eme/MediaKeySystemAccessManager.cpp @@ -83,14 +83,14 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(MediaKeySystemAccessManager) for (size_t i = 0; i < tmp->mPendingInstallRequests.Length(); i++) { tmp->mPendingInstallRequests[i]->CancelTimer(); tmp->mPendingInstallRequests[i]->RejectPromiseWithInvalidAccessError( - NS_LITERAL_CSTRING( + nsLiteralCString( "Promise still outstanding at MediaKeySystemAccessManager GC")); NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingInstallRequests[i]->mPromise) } tmp->mPendingInstallRequests.Clear(); for (size_t i = 0; i < tmp->mPendingAppApprovalRequests.Length(); i++) { tmp->mPendingAppApprovalRequests[i]->RejectPromiseWithInvalidAccessError( - NS_LITERAL_CSTRING( + nsLiteralCString( "Promise still outstanding at MediaKeySystemAccessManager GC")); NS_IMPL_CYCLE_COLLECTION_UNLINK(mPendingAppApprovalRequests[i]->mPromise) } @@ -201,7 +201,7 @@ void MediaKeySystemAccessManager::OnDoesWindowSupportProtectedMedia( if (!aIsSupportedInWindow) { aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("EME is not supported in this window")); + "EME is not supported in this window"_ns); return; } @@ -247,7 +247,7 @@ void MediaKeySystemAccessManager::CheckDoesAppAllowProtectedMedia( MKSAM_LOG_DEBUG( "Failed to create app approval request! Blocking eme request as " "fallback."); - aRequest->RejectPromiseWithInvalidAccessError(NS_LITERAL_CSTRING( + aRequest->RejectPromiseWithInvalidAccessError(nsLiteralCString( "Failed to create approval request to send to app embedding Gecko.")); return; } @@ -329,8 +329,8 @@ void MediaKeySystemAccessManager::OnDoesAppAllowProtectedMedia( NS_ConvertUTF16toUTF8(aRequest->mKeySystem).get()); if (!aIsAllowed) { aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("The application embedding this user agent has " - "blocked MediaKeySystemAccess")); + nsLiteralCString("The application embedding this user agent has " + "blocked MediaKeySystemAccess")); return; } @@ -377,7 +377,7 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( // Not to inform user, because nothing to do if the keySystem is not // supported. aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("Key system is unsupported")); + "Key system is unsupported"_ns); diagnostics.StoreMediaKeySystemAccess( mWindow->GetExtantDoc(), aRequest->mKeySystem, false, __func__); return; @@ -393,8 +393,7 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( MediaKeySystemAccess::NotifyObservers(mWindow, aRequest->mKeySystem, MediaKeySystemStatus::Api_disabled); } - aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("EME has been preffed off")); + aRequest->RejectPromiseWithNotSupportedError("EME has been preffed off"_ns); diagnostics.StoreMediaKeySystemAccess( mWindow->GetExtantDoc(), aRequest->mKeySystem, false, __func__); return; @@ -430,7 +429,7 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( // but can't service this request! Give up. Chrome will still be showing a // "I can't play, updating" notification. aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("Timed out while waiting for a CDM update")); + "Timed out while waiting for a CDM update"_ns); diagnostics.StoreMediaKeySystemAccess( mWindow->GetExtantDoc(), aRequest->mKeySystem, false, __func__); return; @@ -472,9 +471,9 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( if (doc) { Unused << doc->GetDocumentURI(uri); } - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Media"), doc, - nsContentUtils::eDOM_PROPERTIES, aMsgName, params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Media"_ns, + doc, nsContentUtils::eDOM_PROPERTIES, + aMsgName, params); }; bool isPrivateBrowsing = @@ -509,7 +508,7 @@ void MediaKeySystemAccessManager::RequestMediaKeySystemAccess( // Not to inform user, because nothing to do if the corresponding keySystem // configuration is not supported. aRequest->RejectPromiseWithNotSupportedError( - NS_LITERAL_CSTRING("Key system configuration is not supported")); + "Key system configuration is not supported"_ns); diagnostics.StoreMediaKeySystemAccess(mWindow->GetExtantDoc(), aRequest->mKeySystem, false, __func__); } @@ -541,7 +540,7 @@ bool MediaKeySystemAccessManager::AwaitInstall( if (!EnsureObserversAdded()) { NS_WARNING("Failed to add pref observer"); - aRequest->RejectPromiseWithNotSupportedError(NS_LITERAL_CSTRING( + aRequest->RejectPromiseWithNotSupportedError(nsLiteralCString( "Failed trying to setup CDM update: failed adding observers")); return false; } @@ -551,7 +550,7 @@ bool MediaKeySystemAccessManager::AwaitInstall( nsITimer::TYPE_ONE_SHOT); if (!timer) { NS_WARNING("Failed to create timer to await CDM install."); - aRequest->RejectPromiseWithNotSupportedError(NS_LITERAL_CSTRING( + aRequest->RejectPromiseWithNotSupportedError(nsLiteralCString( "Failed trying to setup CDM update: failed timer creation")); return false; } @@ -648,13 +647,13 @@ void MediaKeySystemAccessManager::Shutdown() { mPendingInstallRequests) { // Cancel all requests; we're shutting down. installRequest->CancelTimer(); - installRequest->RejectPromiseWithInvalidAccessError(NS_LITERAL_CSTRING( + installRequest->RejectPromiseWithInvalidAccessError(nsLiteralCString( "Promise still outstanding at MediaKeySystemAccessManager shutdown")); } mPendingInstallRequests.Clear(); for (const UniquePtr& approvalRequest : mPendingAppApprovalRequests) { - approvalRequest->RejectPromiseWithInvalidAccessError(NS_LITERAL_CSTRING( + approvalRequest->RejectPromiseWithInvalidAccessError(nsLiteralCString( "Promise still outstanding at MediaKeySystemAccessManager shutdown")); } mPendingAppApprovalRequests.Clear(); diff --git a/dom/media/eme/MediaKeySystemAccessPermissionRequest.cpp b/dom/media/eme/MediaKeySystemAccessPermissionRequest.cpp index f5306996e65c..1eed629d176b 100644 --- a/dom/media/eme/MediaKeySystemAccessPermissionRequest.cpp +++ b/dom/media/eme/MediaKeySystemAccessPermissionRequest.cpp @@ -40,10 +40,9 @@ MediaKeySystemAccessPermissionRequest::Create(nsPIDOMWindowInner* aWindow) { MediaKeySystemAccessPermissionRequest::MediaKeySystemAccessPermissionRequest( nsGlobalWindowInner* aWindow) - : ContentPermissionRequestBase( - aWindow->GetPrincipal(), aWindow, - NS_LITERAL_CSTRING("media.eme.require-app-approval"), - NS_LITERAL_CSTRING("media-key-system-access")) {} + : ContentPermissionRequestBase(aWindow->GetPrincipal(), aWindow, + "media.eme.require-app-approval"_ns, + "media-key-system-access"_ns) {} MediaKeySystemAccessPermissionRequest:: ~MediaKeySystemAccessPermissionRequest() { diff --git a/dom/media/eme/MediaKeys.cpp b/dom/media/eme/MediaKeys.cpp index a643bb591b0c..cc6f8cfe57ef 100644 --- a/dom/media/eme/MediaKeys.cpp +++ b/dom/media/eme/MediaKeys.cpp @@ -170,7 +170,7 @@ void MediaKeys::GetKeySystem(nsString& aOutKeySystem) const { already_AddRefed MediaKeys::SetServerCertificate( const ArrayBufferViewOrArrayBuffer& aCert, ErrorResult& aRv) { RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeys.setServerCertificate"))); + MakePromise(aRv, "MediaKeys.setServerCertificate"_ns)); if (aRv.Failed()) { return nullptr; } @@ -394,8 +394,7 @@ already_AddRefed MediaKeys::CreateCDMProxy( already_AddRefed MediaKeys::Init(ErrorResult& aRv) { EME_LOG("MediaKeys[%p]::Init()", this); - RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeys::Init()"))); + RefPtr promise(MakePromise(aRv, "MediaKeys::Init()"_ns)); if (aRv.Failed()) { return nullptr; } @@ -623,7 +622,7 @@ void MediaKeys::GetSessionsInfo(nsString& sessionsInfo) { already_AddRefed MediaKeys::GetStatusForPolicy( const MediaKeysPolicy& aPolicy, ErrorResult& aRv) { RefPtr promise( - MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeys::GetStatusForPolicy()"))); + MakePromise(aRv, "MediaKeys::GetStatusForPolicy()"_ns)); if (aRv.Failed()) { return nullptr; } diff --git a/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp b/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp index 68648ab6448a..09d367135f81 100644 --- a/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp +++ b/dom/media/eme/mediadrm/MediaDrmCDMProxy.cpp @@ -54,7 +54,7 @@ void MediaDrmCDMProxy::Init(PromiseId aPromiseId, const nsAString& aOrigin, NS_NewNamedThread("MDCDMThread", getter_AddRefs(mOwnerThread)); if (NS_FAILED(rv)) { RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING( + aPromiseId, nsLiteralCString( "Couldn't create CDM thread MediaDrmCDMProxy::Init")); return; } @@ -93,8 +93,7 @@ void MediaDrmCDMProxy::LoadSession(PromiseId aPromiseId, const nsAString& aSessionId) { // TODO: Implement LoadSession. RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Currently Fennec does not support LoadSession")); + aPromiseId, "Currently Fennec does not support LoadSession"_ns); } void MediaDrmCDMProxy::SetServerCertificate(PromiseId aPromiseId, @@ -147,8 +146,7 @@ void MediaDrmCDMProxy::RemoveSession(const nsAString& aSessionId, PromiseId aPromiseId) { // TODO: Implement RemoveSession. RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Currently Fennec does not support RemoveSession")); + aPromiseId, "Currently Fennec does not support RemoveSession"_ns); } void MediaDrmCDMProxy::Shutdown() { @@ -383,8 +381,8 @@ void MediaDrmCDMProxy::md_CreateSession(UniquePtr&& aData) { MOZ_ASSERT(IsOnOwnerThread()); if (!mCDM) { - RejectPromiseWithStateError( - aData->mPromiseId, NS_LITERAL_CSTRING("Null CDM in md_CreateSession")); + RejectPromiseWithStateError(aData->mPromiseId, + "Null CDM in md_CreateSession"_ns); return; } @@ -398,8 +396,8 @@ void MediaDrmCDMProxy::md_SetServerCertificate(PromiseId aPromiseId, MOZ_ASSERT(IsOnOwnerThread()); if (!mCDM) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in md_SetServerCertificate")); + RejectPromiseWithStateError(aPromiseId, + "Null CDM in md_SetServerCertificate"_ns); return; } @@ -407,8 +405,7 @@ void MediaDrmCDMProxy::md_SetServerCertificate(PromiseId aPromiseId, ResolvePromiseWithResult(aPromiseId, true); } else { RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING( - "MediaDrmCDMProxy unable to set server certificate")); + aPromiseId, "MediaDrmCDMProxy unable to set server certificate"_ns); } } @@ -416,8 +413,8 @@ void MediaDrmCDMProxy::md_UpdateSession(UniquePtr&& aData) { MOZ_ASSERT(IsOnOwnerThread()); if (!mCDM) { - RejectPromiseWithStateError( - aData->mPromiseId, NS_LITERAL_CSTRING("Null CDM in md_UpdateSession")); + RejectPromiseWithStateError(aData->mPromiseId, + "Null CDM in md_UpdateSession"_ns); return; } mCDM->UpdateSession(aData->mPromiseId, aData->mSessionId, aData->mResponse); @@ -427,8 +424,8 @@ void MediaDrmCDMProxy::md_CloseSession(UniquePtr&& aData) { MOZ_ASSERT(IsOnOwnerThread()); if (!mCDM) { - RejectPromiseWithStateError( - aData->mPromiseId, NS_LITERAL_CSTRING("Null CDM in md_CloseSession")); + RejectPromiseWithStateError(aData->mPromiseId, + "Null CDM in md_CloseSession"_ns); return; } mCDM->CloseSession(aData->mPromiseId, aData->mSessionId); diff --git a/dom/media/encoder/OpusTrackEncoder.cpp b/dom/media/encoder/OpusTrackEncoder.cpp index feae3d6ed7c2..d247c1d18198 100644 --- a/dom/media/encoder/OpusTrackEncoder.cpp +++ b/dom/media/encoder/OpusTrackEncoder.cpp @@ -220,7 +220,7 @@ already_AddRefed OpusTrackEncoder::GetMetadata() { nsTArray comments; comments.AppendElement( - NS_LITERAL_CSTRING("ENCODER=Mozilla" MOZ_APP_UA_VERSION)); + nsLiteralCString("ENCODER=Mozilla" MOZ_APP_UA_VERSION)); SerializeOpusCommentHeader(vendor, comments, &meta->mCommentHeader); diff --git a/dom/media/flac/FlacDecoder.cpp b/dom/media/flac/FlacDecoder.cpp index 2796119f88ba..52fa84db474e 100644 --- a/dom/media/flac/FlacDecoder.cpp +++ b/dom/media/flac/FlacDecoder.cpp @@ -38,7 +38,7 @@ nsTArray> FlacDecoder::GetTracksInfo( tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/flac"), aType)); + "audio/flac"_ns, aType)); return tracks; } diff --git a/dom/media/gmp/ChromiumCDMParent.cpp b/dom/media/gmp/ChromiumCDMParent.cpp index a40c6a75b799..c2d880b63ca1 100644 --- a/dom/media/gmp/ChromiumCDMParent.cpp +++ b/dom/media/gmp/ChromiumCDMParent.cpp @@ -128,8 +128,7 @@ void ChromiumCDMParent::CreateSession(uint32_t aCreateSessionToken, if (!SendCreateSessionAndGenerateRequest(aPromiseId, aSessionType, aInitDataType, aInitData)) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send generateRequest to CDM process.")); + aPromiseId, "Failed to send generateRequest to CDM process."_ns); return; } mPromiseToCreateSessionToken.Put(aPromiseId, aCreateSessionToken); @@ -147,8 +146,7 @@ void ChromiumCDMParent::LoadSession(uint32_t aPromiseId, uint32_t aSessionType, if (!SendLoadSession(aPromiseId, aSessionType, NS_ConvertUTF16toUTF8(aSessionId))) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send loadSession to CDM process.")); + aPromiseId, "Failed to send loadSession to CDM process."_ns); return; } } @@ -162,8 +160,7 @@ void ChromiumCDMParent::SetServerCertificate(uint32_t aPromiseId, } if (!SendSetServerCertificate(aPromiseId, aCert)) { RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING( - "Failed to send setServerCertificate to CDM process")); + aPromiseId, "Failed to send setServerCertificate to CDM process"_ns); } } @@ -177,8 +174,7 @@ void ChromiumCDMParent::UpdateSession(const nsCString& aSessionId, } if (!SendUpdateSession(aPromiseId, aSessionId, aResponse)) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send updateSession to CDM process")); + aPromiseId, "Failed to send updateSession to CDM process"_ns); } } @@ -191,8 +187,7 @@ void ChromiumCDMParent::CloseSession(const nsCString& aSessionId, } if (!SendCloseSession(aPromiseId, aSessionId)) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send closeSession to CDM process")); + aPromiseId, "Failed to send closeSession to CDM process"_ns); } } @@ -205,8 +200,7 @@ void ChromiumCDMParent::RemoveSession(const nsCString& aSessionId, } if (!SendRemoveSession(aPromiseId, aSessionId)) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send removeSession to CDM process")); + aPromiseId, "Failed to send removeSession to CDM process"_ns); } } @@ -271,8 +265,7 @@ void ChromiumCDMParent::GetStatusForPolicy(uint32_t aPromiseId, if (!SendGetStatusForPolicy(aPromiseId, hdcpVersionResult.unwrap())) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Failed to send getStatusForPolicy to CDM process")); + aPromiseId, "Failed to send getStatusForPolicy to CDM process"_ns); } } @@ -412,8 +405,8 @@ ipc::IPCResult ChromiumCDMParent::RecvOnResolveNewSessionPromise( Maybe token = mPromiseToCreateSessionToken.GetAndRemove(aPromiseId); if (token.isNothing()) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Lost session token for new session.")); + RejectPromiseWithStateError(aPromiseId, + "Lost session token for new session."_ns); return IPC_OK(); } @@ -473,8 +466,7 @@ void ChromiumCDMParent::RejectPromise(uint32_t aPromiseId, } void ChromiumCDMParent::RejectPromiseShutdown(uint32_t aPromiseId) { - RejectPromiseWithStateError(aPromiseId, - NS_LITERAL_CSTRING("CDM is shutdown")); + RejectPromiseWithStateError(aPromiseId, "CDM is shutdown"_ns); } void ChromiumCDMParent::RejectPromiseWithStateError( diff --git a/dom/media/gmp/ChromiumCDMProxy.cpp b/dom/media/gmp/ChromiumCDMProxy.cpp index 8a7a459b9c0c..9068d6138e09 100644 --- a/dom/media/gmp/ChromiumCDMProxy.cpp +++ b/dom/media/gmp/ChromiumCDMProxy.cpp @@ -53,8 +53,7 @@ void ChromiumCDMProxy::Init(PromiseId aPromiseId, const nsAString& aOrigin, if (!mGMPThread) { RejectPromiseWithStateError( - aPromiseId, - NS_LITERAL_CSTRING("Couldn't get GMP thread ChromiumCDMProxy::Init")); + aPromiseId, "Couldn't get GMP thread ChromiumCDMProxy::Init"_ns); return; } @@ -79,8 +78,8 @@ void ChromiumCDMProxy::Init(PromiseId aPromiseId, const nsAString& aOrigin, if (!service) { self->RejectPromiseWithStateError( aPromiseId, - NS_LITERAL_CSTRING("Couldn't get GeckoMediaPluginService in " - "ChromiumCDMProxy::Init")); + nsLiteralCString("Couldn't get GeckoMediaPluginService in " + "ChromiumCDMProxy::Init")); return; } RefPtr promise = @@ -104,7 +103,7 @@ void ChromiumCDMProxy::Init(PromiseId aPromiseId, const nsAString& aOrigin, } if (self->mIsShutdown) { self->RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING( + aPromiseId, nsLiteralCString( "ChromiumCDMProxy shutdown " "during ChromiumCDMProxy::Init")); // If shutdown happened while waiting to init, we @@ -234,8 +233,7 @@ void ChromiumCDMProxy::CreateSession(uint32_t aCreateSessionToken, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in CreateSession")); + RejectPromiseWithStateError(aPromiseId, "Null CDM in CreateSession"_ns); return; } @@ -253,8 +251,7 @@ void ChromiumCDMProxy::LoadSession(PromiseId aPromiseId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError(aPromiseId, - NS_LITERAL_CSTRING("Null CDM in LoadSession")); + RejectPromiseWithStateError(aPromiseId, "Null CDM in LoadSession"_ns); return; } @@ -273,8 +270,8 @@ void ChromiumCDMProxy::SetServerCertificate(PromiseId aPromiseId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in SetServerCertificate")); + RejectPromiseWithStateError(aPromiseId, + "Null CDM in SetServerCertificate"_ns); return; } @@ -296,8 +293,7 @@ void ChromiumCDMProxy::UpdateSession(const nsAString& aSessionId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in UpdateSession")); + RejectPromiseWithStateError(aPromiseId, "Null CDM in UpdateSession"_ns); return; } mGMPThread->Dispatch( @@ -315,8 +311,7 @@ void ChromiumCDMProxy::CloseSession(const nsAString& aSessionId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError(aPromiseId, - NS_LITERAL_CSTRING("Null CDM in CloseSession")); + RejectPromiseWithStateError(aPromiseId, "Null CDM in CloseSession"_ns); return; } mGMPThread->Dispatch(NewRunnableMethod( @@ -333,8 +328,7 @@ void ChromiumCDMProxy::RemoveSession(const nsAString& aSessionId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in RemoveSession")); + RejectPromiseWithStateError(aPromiseId, "Null CDM in RemoveSession"_ns); return; } mGMPThread->Dispatch(NewRunnableMethod( @@ -558,8 +552,8 @@ void ChromiumCDMProxy::GetStatusForPolicy(PromiseId aPromiseId, RefPtr cdm = GetCDMParent(); if (!cdm) { - RejectPromiseWithStateError( - aPromiseId, NS_LITERAL_CSTRING("Null CDM in GetStatusForPolicy")); + RejectPromiseWithStateError(aPromiseId, + "Null CDM in GetStatusForPolicy"_ns); return; } diff --git a/dom/media/gmp/GMPChild.cpp b/dom/media/gmp/GMPChild.cpp index 24a6686e33b0..48220d0f8fb2 100644 --- a/dom/media/gmp/GMPChild.cpp +++ b/dom/media/gmp/GMPChild.cpp @@ -99,13 +99,11 @@ static bool GetPluginFile(const nsAString& aPluginPath, GetFileBase(aPluginPath, aLibDirectory, aLibFile, baseName); #if defined(XP_MACOSX) - nsAutoString binaryName = - NS_LITERAL_STRING("lib") + baseName + NS_LITERAL_STRING(".dylib"); + nsAutoString binaryName = u"lib"_ns + baseName + u".dylib"_ns; #elif defined(OS_POSIX) - nsAutoString binaryName = - NS_LITERAL_STRING("lib") + baseName + NS_LITERAL_STRING(".so"); + nsAutoString binaryName = u"lib"_ns + baseName + u".so"_ns; #elif defined(XP_WIN) - nsAutoString binaryName = baseName + NS_LITERAL_STRING(".dll"); + nsAutoString binaryName = baseName + u".dll"_ns; #else # error not defined #endif @@ -315,14 +313,14 @@ static bool IsFileLeafEqualToASCII(const nsCOMPtr& aFile, #endif #if defined(XP_WIN) -# define FIREFOX_FILE NS_LITERAL_STRING("firefox.exe") -# define XUL_LIB_FILE NS_LITERAL_STRING("xul.dll") +# define FIREFOX_FILE u"firefox.exe"_ns +# define XUL_LIB_FILE u"xul.dll"_ns #elif defined(XP_MACOSX) -# define FIREFOX_FILE NS_LITERAL_STRING("firefox") -# define XUL_LIB_FILE NS_LITERAL_STRING("XUL") +# define FIREFOX_FILE u"firefox"_ns +# define XUL_LIB_FILE u"XUL"_ns #else -# define FIREFOX_FILE NS_LITERAL_STRING("firefox") -# define XUL_LIB_FILE NS_LITERAL_STRING("libxul.so") +# define FIREFOX_FILE u"firefox"_ns +# define XUL_LIB_FILE u"libxul.so"_ns #endif static nsCOMPtr GetFirefoxAppPath( @@ -374,7 +372,7 @@ static bool GetSigPath(const int aRelativeLayers, } MOZ_ASSERT(path); aOutSigPath = path; - return NS_SUCCEEDED(path->Append(NS_LITERAL_STRING("Resources"))) && + return NS_SUCCEEDED(path->Append(u"Resources"_ns)) && NS_SUCCEEDED(path->Append(aTargetSigFileName)); } #endif @@ -394,7 +392,7 @@ static bool AppendHostPath(nsCOMPtr& aFile, if (NS_FAILED(aFile->GetLeafName(binary))) { return false; } - binary.Append(NS_LITERAL_STRING(".sig")); + binary.Append(u".sig"_ns); nsCOMPtr sigFile; if (GetSigPath(2, binary, aFile, sigFile) && NS_SUCCEEDED(sigFile->GetPath(str))) { @@ -403,12 +401,10 @@ static bool AppendHostPath(nsCOMPtr& aFile, // Cannot successfully get the sig file path. // Assume it is located at the same place as plugin-container // alternatively. - sigFilePath = - nsCString(NS_ConvertUTF16toUTF8(str) + NS_LITERAL_CSTRING(".sig")); + sigFilePath = nsCString(NS_ConvertUTF16toUTF8(str) + ".sig"_ns); } #else - sigFilePath = - nsCString(NS_ConvertUTF16toUTF8(str) + NS_LITERAL_CSTRING(".sig")); + sigFilePath = nsCString(NS_ConvertUTF16toUTF8(str) + ".sig"_ns); #endif aPaths.AppendElement( std::make_pair(std::move(filePath), std::move(sigFilePath))); @@ -424,9 +420,9 @@ GMPChild::MakeCDMHostVerificationPaths() { nsString str; if (GetPluginFile(mPluginPath, path) && FileExists(path) && ResolveLinks(path) && NS_SUCCEEDED(path->GetPath(str))) { - paths.AppendElement(std::make_pair( - nsCString(NS_ConvertUTF16toUTF8(str)), - nsCString(NS_ConvertUTF16toUTF8(str) + NS_LITERAL_CSTRING(".sig")))); + paths.AppendElement( + std::make_pair(nsCString(NS_ConvertUTF16toUTF8(str)), + nsCString(NS_ConvertUTF16toUTF8(str) + ".sig"_ns))); } // Plugin-container binary path. diff --git a/dom/media/gmp/GMPDiskStorage.cpp b/dom/media/gmp/GMPDiskStorage.cpp index ae5721a33c34..6f7f8bf93932 100644 --- a/dom/media/gmp/GMPDiskStorage.cpp +++ b/dom/media/gmp/GMPDiskStorage.cpp @@ -44,7 +44,7 @@ static nsresult GetGMPStorageDir(nsIFile** aTempDir, const nsString& aGMPName, return rv; } - rv = tmpFile->AppendNative(NS_LITERAL_CSTRING("storage")); + rv = tmpFile->AppendNative("storage"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/media/gmp/GMPParent.cpp b/dom/media/gmp/GMPParent.cpp index 98fa77880be5..eeb10547c97a 100644 --- a/dom/media/gmp/GMPParent.cpp +++ b/dom/media/gmp/GMPParent.cpp @@ -467,11 +467,9 @@ static void GMPNotifyObservers(const uint32_t aPluginID, nsCOMPtr propbag = do_CreateInstance("@mozilla.org/hash-property-bag;1"); if (obs && propbag) { - propbag->SetPropertyAsUint32(NS_LITERAL_STRING("pluginID"), aPluginID); - propbag->SetPropertyAsACString(NS_LITERAL_STRING("pluginName"), - aPluginName); - propbag->SetPropertyAsAString(NS_LITERAL_STRING("pluginDumpID"), - aPluginDumpID); + propbag->SetPropertyAsUint32(u"pluginID"_ns, aPluginID); + propbag->SetPropertyAsACString(u"pluginName"_ns, aPluginName); + propbag->SetPropertyAsAString(u"pluginDumpID"_ns, aPluginDumpID); obs->NotifyObservers(propbag, "gmp-plugin-crash", nullptr); } @@ -486,8 +484,8 @@ void GMPParent::ActorDestroy(ActorDestroyReason aWhy) { GMP_PARENT_LOG_DEBUG("%s: (%d)", __FUNCTION__, (int)aWhy); if (AbnormalShutdown == aWhy) { - Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, - NS_LITERAL_CSTRING("gmplugin"), 1); + Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, "gmplugin"_ns, + 1); nsString dumpID; GetCrashID(dumpID); if (dumpID.IsEmpty()) { @@ -580,7 +578,7 @@ RefPtr GMPParent::ReadGMPMetaData() { if (NS_WARN_IF(NS_FAILED(rv))) { return GenericPromise::CreateAndReject(rv, __func__); } - infoFile->AppendRelativePath(mName + NS_LITERAL_STRING(".info")); + infoFile->AppendRelativePath(mName + u".info"_ns); if (FileExists(infoFile)) { return ReadGMPInfoFile(infoFile); @@ -592,7 +590,7 @@ RefPtr GMPParent::ReadGMPMetaData() { if (NS_WARN_IF(NS_FAILED(rv))) { return GenericPromise::CreateAndReject(rv, __func__); } - manifestFile->AppendRelativePath(NS_LITERAL_STRING("manifest.json")); + manifestFile->AppendRelativePath(u"manifest.json"_ns); return ReadChromiumManifestFile(manifestFile); } @@ -603,16 +601,16 @@ RefPtr GMPParent::ReadGMPInfoFile(nsIFile* aFile) { } nsAutoCString apis; - if (!ReadInfoField(parser, NS_LITERAL_CSTRING("name"), mDisplayName) || - !ReadInfoField(parser, NS_LITERAL_CSTRING("description"), mDescription) || - !ReadInfoField(parser, NS_LITERAL_CSTRING("version"), mVersion) || - !ReadInfoField(parser, NS_LITERAL_CSTRING("apis"), apis)) { + if (!ReadInfoField(parser, "name"_ns, mDisplayName) || + !ReadInfoField(parser, "description"_ns, mDescription) || + !ReadInfoField(parser, "version"_ns, mVersion) || + !ReadInfoField(parser, "apis"_ns, apis)) { return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__); } #if defined(XP_WIN) || defined(XP_LINUX) // "Libraries" field is optional. - ReadInfoField(parser, NS_LITERAL_CSTRING("libraries"), mLibs); + ReadInfoField(parser, "libraries"_ns, mLibs); #endif nsTArray apiTokens; @@ -723,23 +721,23 @@ RefPtr GMPParent::ParseChromiumManifest( if (mDisplayName.EqualsASCII("clearkey")) { kEMEKeySystem.AssignLiteral(EME_KEY_SYSTEM_CLEARKEY); #if XP_WIN - mLibs = NS_LITERAL_CSTRING( + mLibs = nsLiteralCString( "dxva2.dll, evr.dll, freebl3.dll, mfh264dec.dll, mfplat.dll, " "msmpeg2vdec.dll, nss3.dll, softokn3.dll"); #elif XP_LINUX - mLibs = NS_LITERAL_CSTRING("libfreeblpriv3.so, libsoftokn3.so"); + mLibs = "libfreeblpriv3.so, libsoftokn3.so"_ns; #endif } else if (mDisplayName.EqualsASCII("WidevineCdm")) { kEMEKeySystem.AssignLiteral(EME_KEY_SYSTEM_WIDEVINE); #if XP_WIN // psapi.dll added for GetMappedFileNameW, which could possibly be avoided // in future versions, see bug 1383611 for details. - mLibs = NS_LITERAL_CSTRING("dxva2.dll, psapi.dll"); + mLibs = "dxva2.dll, psapi.dll"_ns; #endif } else if (mDisplayName.EqualsASCII("fake")) { kEMEKeySystem.AssignLiteral("fake"); #if XP_WIN - mLibs = NS_LITERAL_CSTRING("dxva2.dll"); + mLibs = "dxva2.dll"_ns; #endif } else { GMP_PARENT_LOG_DEBUG("%s: Unrecognized key system: %s, failing.", @@ -765,13 +763,13 @@ RefPtr GMPParent::ParseChromiumManifest( for (const nsCString& chromiumCodec : codecs) { nsCString codec; if (chromiumCodec.EqualsASCII("vp8")) { - codec = NS_LITERAL_CSTRING("vp8"); + codec = "vp8"_ns; } else if (chromiumCodec.EqualsASCII("vp9.0")) { - codec = NS_LITERAL_CSTRING("vp9"); + codec = "vp9"_ns; } else if (chromiumCodec.EqualsASCII("avc1")) { - codec = NS_LITERAL_CSTRING("h264"); + codec = "h264"_ns; } else if (chromiumCodec.EqualsASCII("av01")) { - codec = NS_LITERAL_CSTRING("av1"); + codec = "av1"_ns; } else { GMP_PARENT_LOG_DEBUG("%s: Unrecognized codec: %s, failing.", __FUNCTION__, chromiumCodec.get()); @@ -783,8 +781,8 @@ RefPtr GMPParent::ParseChromiumManifest( video.mAPITags.AppendElement(kEMEKeySystem); - video.mAPIName = NS_LITERAL_CSTRING(CHROMIUM_CDM_API); - mAdapter = NS_LITERAL_STRING("chromium"); + video.mAPIName = nsLiteralCString(CHROMIUM_CDM_API); + mAdapter = u"chromium"_ns; mCapabilities.AppendElement(std::move(video)); @@ -907,9 +905,7 @@ bool GMPParent::EnsureProcessLoaded(base::ProcessId* aID) { void GMPParent::IncrementGMPContentChildCount() { ++mGMPContentChildCount; } -nsString GMPParent::GetPluginBaseName() const { - return NS_LITERAL_STRING("gmp-") + mName; -} +nsString GMPParent::GetPluginBaseName() const { return u"gmp-"_ns + mName; } } // namespace gmp } // namespace mozilla diff --git a/dom/media/gmp/GMPService.cpp b/dom/media/gmp/GMPService.cpp index db40c4f59a33..5ad31d1680ee 100644 --- a/dom/media/gmp/GMPService.cpp +++ b/dom/media/gmp/GMPService.cpp @@ -179,8 +179,8 @@ GeckoMediaPluginService::RunPluginCrashCallbacks( CopyUTF8toUTF16(aPluginName, init.mPluginName); init.mSubmittedCrashReport = false; RefPtr event = - dom::PluginCrashedEvent::Constructor( - document, NS_LITERAL_STRING("PluginCrashed"), init); + dom::PluginCrashedEvent::Constructor(document, u"PluginCrashed"_ns, + init); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; @@ -223,8 +223,7 @@ RefPtr GeckoMediaPluginService::GetCDM( RefPtr promise = rawHolder->Ensure(__func__); RefPtr thread(GetAbstractGMPThread()); RefPtr helper(aHelper); - GetContentParent(aHelper, aNodeId, NS_LITERAL_CSTRING(CHROMIUM_CDM_API), - aTags) + GetContentParent(aHelper, aNodeId, nsLiteralCString(CHROMIUM_CDM_API), aTags) ->Then( thread, __func__, [rawHolder, helper](RefPtr wrapper) { @@ -345,7 +344,7 @@ GeckoMediaPluginService::GetDecryptingGMPVideoDecoder( GetGMPVideoDecoderCallback* rawCallback = aCallback.release(); RefPtr thread(GetAbstractGMPThread()); RefPtr helper(aHelper); - GetContentParent(aHelper, aNodeId, NS_LITERAL_CSTRING(GMP_API_VIDEO_DECODER), + GetContentParent(aHelper, aNodeId, nsLiteralCString(GMP_API_VIDEO_DECODER), *aTags) ->Then( thread, __func__, @@ -386,7 +385,7 @@ GeckoMediaPluginService::GetGMPVideoEncoder( GetGMPVideoEncoderCallback* rawCallback = aCallback.release(); RefPtr thread(GetAbstractGMPThread()); RefPtr helper(aHelper); - GetContentParent(aHelper, aNodeId, NS_LITERAL_CSTRING(GMP_API_VIDEO_ENCODER), + GetContentParent(aHelper, aNodeId, nsLiteralCString(GMP_API_VIDEO_ENCODER), *aTags) ->Then( thread, __func__, diff --git a/dom/media/gmp/GMPServiceChild.cpp b/dom/media/gmp/GMPServiceChild.cpp index 1eede36de71a..c81a4105fc7d 100644 --- a/dom/media/gmp/GMPServiceChild.cpp +++ b/dom/media/gmp/GMPServiceChild.cpp @@ -76,7 +76,7 @@ GeckoMediaPluginServiceChild::GetContentParent( nsCString displayName; uint32_t pluginId = 0; ipc::Endpoint endpoint; - nsCString errorDescription = NS_LITERAL_CSTRING(""); + nsCString errorDescription = ""_ns; bool ok = child->SendLaunchGMP( nodeIdString, api, tags, alreadyBridgedTo, &pluginId, &otherProcess, @@ -152,7 +152,7 @@ GeckoMediaPluginServiceChild::GetContentParent( nsCString displayName; uint32_t pluginId = 0; ipc::Endpoint endpoint; - nsCString errorDescription = NS_LITERAL_CSTRING(""); + nsCString errorDescription = ""_ns; bool ok = child->SendLaunchGMPForNodeId( nodeId, api, tags, alreadyBridgedTo, &pluginId, &otherProcess, diff --git a/dom/media/gmp/GMPServiceParent.cpp b/dom/media/gmp/GMPServiceParent.cpp index 10211ec207ca..8d6653423d62 100644 --- a/dom/media/gmp/GMPServiceParent.cpp +++ b/dom/media/gmp/GMPServiceParent.cpp @@ -198,7 +198,7 @@ nsresult GeckoMediaPluginServiceParent::InitStorage() { return rv; } - rv = mStorageBaseDir->AppendNative(NS_LITERAL_CSTRING("gmp")); + rv = mStorageBaseDir->AppendNative("gmp"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -227,7 +227,7 @@ GeckoMediaPluginServiceParent::Observe(nsISupports* aSubject, nsCOMPtr branch(do_QueryInterface(aSubject)); if (branch) { bool crashNow = false; - if (NS_LITERAL_STRING("media.gmp.plugin.crash").Equals(aSomeData)) { + if (u"media.gmp.plugin.crash"_ns.Equals(aSomeData)) { branch->GetBoolPref("media.gmp.plugin.crash", &crashNow); } if (crashNow) { @@ -1033,8 +1033,7 @@ static nsresult ReadFromFile(nsIFile* aPath, const nsACString& aFileName, } nsresult ReadSalt(nsIFile* aPath, nsACString& aOutData) { - return ReadFromFile(aPath, NS_LITERAL_CSTRING("salt"), aOutData, - NodeIdSaltLength); + return ReadFromFile(aPath, "salt"_ns, aOutData, NodeIdSaltLength); } already_AddRefed GeckoMediaPluginServiceParent::GetMemoryStorageFor( @@ -1126,7 +1125,7 @@ nsresult GeckoMediaPluginServiceParent::GetNodeId( } // $profileDir/gmp/$platform/$gmpName/id/ - rv = path->AppendNative(NS_LITERAL_CSTRING("id")); + rv = path->AppendNative("id"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1151,7 +1150,7 @@ nsresult GeckoMediaPluginServiceParent::GetNodeId( return rv; } - rv = saltFile->AppendNative(NS_LITERAL_CSTRING("salt")); + rv = saltFile->AppendNative("salt"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1172,20 +1171,19 @@ nsresult GeckoMediaPluginServiceParent::GetNodeId( MOZ_ASSERT(salt.Length() == NodeIdSaltLength); // $profileDir/gmp/$platform/$gmpName/id/$hash/salt - rv = WriteToFile(path, NS_LITERAL_CSTRING("salt"), salt); + rv = WriteToFile(path, "salt"_ns, salt); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // $profileDir/gmp/$platform/$gmpName/id/$hash/origin - rv = WriteToFile(path, NS_LITERAL_CSTRING("origin"), - NS_ConvertUTF16toUTF8(aOrigin)); + rv = WriteToFile(path, "origin"_ns, NS_ConvertUTF16toUTF8(aOrigin)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // $profileDir/gmp/$platform/$gmpName/id/$hash/topLevelOrigin - rv = WriteToFile(path, NS_LITERAL_CSTRING("topLevelOrigin"), + rv = WriteToFile(path, "topLevelOrigin"_ns, NS_ConvertUTF16toUTF8(aTopLevelOrigin)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -1244,7 +1242,7 @@ bool MatchOrigin(nsIFile* aPath, const nsACString& aSite, nsCString originNoSuffix; mozilla::OriginAttributes originAttributes; - rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("origin"), str, MaxDomainLength); + rv = ReadFromFile(aPath, "origin"_ns, str, MaxDomainLength); if (!originAttributes.PopulateFromOrigin(str, originNoSuffix)) { // Fails on parsing the originAttributes, treat this as a non-match. return false; @@ -1256,8 +1254,7 @@ bool MatchOrigin(nsIFile* aPath, const nsACString& aSite, } mozilla::OriginAttributes topLevelOriginAttributes; - rv = ReadFromFile(aPath, NS_LITERAL_CSTRING("topLevelOrigin"), str, - MaxDomainLength); + rv = ReadFromFile(aPath, "topLevelOrigin"_ns, str, MaxDomainLength); if (!topLevelOriginAttributes.PopulateFromOrigin(str, originNoSuffix)) { // Fails on paring the originAttributes, treat this as a non-match. return false; @@ -1325,8 +1322,7 @@ void GeckoMediaPluginServiceParent::ClearNodeIdAndPlugin( void GeckoMediaPluginServiceParent::ClearNodeIdAndPlugin( nsIFile* aPluginStorageDir, DirectoryFilter& aFilter) { // $profileDir/gmp/$platform/$gmpName/id/ - nsCOMPtr path = - CloneAndAppend(aPluginStorageDir, NS_LITERAL_STRING("id")); + nsCOMPtr path = CloneAndAppend(aPluginStorageDir, u"id"_ns); if (!path) { return; } @@ -1357,7 +1353,7 @@ void GeckoMediaPluginServiceParent::ClearNodeIdAndPlugin( KillPlugins(mPlugins, mMutex, NodeFilter(nodeIDsToClear)); // Clear all storage in $profileDir/gmp/$platform/$gmpName/storage/$nodeId/ - path = CloneAndAppend(aPluginStorageDir, NS_LITERAL_STRING("storage")); + path = CloneAndAppend(aPluginStorageDir, u"storage"_ns); if (!path) { return; } @@ -1449,7 +1445,7 @@ void GeckoMediaPluginServiceParent::ClearRecentHistoryOnGMPThread( } // $profileDir/gmp/$platform/$gmpName/storage/ - if (NS_WARN_IF(NS_FAILED(temp->Append(NS_LITERAL_STRING("storage"))))) { + if (NS_WARN_IF(NS_FAILED(temp->Append(u"storage"_ns)))) { return false; } // $profileDir/gmp/$platform/$gmpName/storage/$originSalt @@ -1510,7 +1506,7 @@ static nsCOMPtr GetShutdownBarrier() { NS_IMETHODIMP GeckoMediaPluginServiceParent::GetName(nsAString& aName) { - aName = NS_LITERAL_STRING("GeckoMediaPluginServiceParent: shutdown"); + aName = u"GeckoMediaPluginServiceParent: shutdown"_ns; return NS_OK; } @@ -1531,7 +1527,7 @@ void GeckoMediaPluginServiceParent::ServiceUserCreated( if (mServiceParents.Length() == 1) { nsresult rv = GetShutdownBarrier()->AddBlocker( this, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("GeckoMediaPluginServiceParent shutdown")); + u"GeckoMediaPluginServiceParent shutdown"_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } @@ -1604,7 +1600,7 @@ mozilla::ipc::IPCResult GMPServiceParent::RecvLaunchGMP( nsresult* aOutRv, nsCString* aOutErrorDescription) { if (mService->IsShuttingDown()) { *aOutRv = NS_ERROR_ILLEGAL_DURING_SHUTDOWN; - *aOutErrorDescription = NS_LITERAL_CSTRING("Service is shutting down."); + *aOutErrorDescription = "Service is shutting down."_ns; return IPC_OK(); } @@ -1613,15 +1609,14 @@ mozilla::ipc::IPCResult GMPServiceParent::RecvLaunchGMP( *aOutPluginId = gmp->GetPluginId(); } else { *aOutRv = NS_ERROR_FAILURE; - *aOutErrorDescription = - NS_LITERAL_CSTRING("SelectPluginForAPI returns nullptr."); + *aOutErrorDescription = "SelectPluginForAPI returns nullptr."_ns; *aOutPluginId = 0; return IPC_OK(); } if (!gmp->EnsureProcessLoaded(aOutProcessId)) { *aOutRv = NS_ERROR_FAILURE; - *aOutErrorDescription = NS_LITERAL_CSTRING("Process has not loaded."); + *aOutErrorDescription = "Process has not loaded."_ns; return IPC_OK(); } @@ -1638,8 +1633,7 @@ mozilla::ipc::IPCResult GMPServiceParent::RecvLaunchGMP( PGMPContent::CreateEndpoints(OtherPid(), *aOutProcessId, &parent, &child); if (NS_WARN_IF(NS_FAILED(rv))) { *aOutRv = rv; - *aOutErrorDescription = - NS_LITERAL_CSTRING("PGMPContent::CreateEndpoints failed."); + *aOutErrorDescription = "PGMPContent::CreateEndpoints failed."_ns; return IPC_OK(); } @@ -1647,8 +1641,7 @@ mozilla::ipc::IPCResult GMPServiceParent::RecvLaunchGMP( if (!gmp->SendInitGMPContentChild(std::move(child))) { *aOutRv = NS_ERROR_FAILURE; - *aOutErrorDescription = - NS_LITERAL_CSTRING("SendInitGMPContentChild failed."); + *aOutErrorDescription = "SendInitGMPContentChild failed."_ns; return IPC_OK(); } @@ -1669,7 +1662,7 @@ mozilla::ipc::IPCResult GMPServiceParent::RecvLaunchGMPForNodeId( aNodeId.mOrigin(), aNodeId.mTopLevelOrigin(), aNodeId.mGMPName(), nodeId); if (!NS_SUCCEEDED(rv)) { *aOutRv = rv; - *aOutErrorDescription = NS_LITERAL_CSTRING("GetNodeId failed."); + *aOutErrorDescription = "GetNodeId failed."_ns; return IPC_OK(); } return RecvLaunchGMP(nodeId, aApi, std::move(aTags), diff --git a/dom/media/gmp/GMPVideoDecoderParent.cpp b/dom/media/gmp/GMPVideoDecoderParent.cpp index 3a084599c67f..96005b2efc25 100644 --- a/dom/media/gmp/GMPVideoDecoderParent.cpp +++ b/dom/media/gmp/GMPVideoDecoderParent.cpp @@ -176,8 +176,8 @@ nsresult GMPVideoDecoderParent::Reset() { "waiting for ResetComplete", self.get()); self->mResetCompleteTimeout = nullptr; - LogToBrowserConsole(NS_LITERAL_STRING( - "GMPVideoDecoderParent timed out waiting for ResetComplete()")); + LogToBrowserConsole(nsLiteralString( + u"GMPVideoDecoderParent timed out waiting for ResetComplete()")); }); CancelResetCompleteTimeout(); nsCOMPtr target = mPlugin->GMPEventTarget(); diff --git a/dom/media/gtest/TestAudioDeviceEnumerator.cpp b/dom/media/gtest/TestAudioDeviceEnumerator.cpp index 60dfd99299f0..58ca2a98226b 100644 --- a/dom/media/gtest/TestAudioDeviceEnumerator.cpp +++ b/dom/media/gtest/TestAudioDeviceEnumerator.cpp @@ -217,7 +217,7 @@ TEST(CubebDeviceEnumerator, DeviceInfoFromName) cubeb_devid id_1 = reinterpret_cast(1); mock->AddDevice(DeviceTemplate(id_1, deviceType, "device name 1")); cubeb_devid id_2 = reinterpret_cast(2); - nsCString device_name = NS_LITERAL_CSTRING("device name 2"); + nsCString device_name = "device name 2"_ns; mock->AddDevice(DeviceTemplate(id_2, deviceType, device_name.get())); cubeb_devid id_3 = reinterpret_cast(3); mock->AddDevice(DeviceTemplate(id_3, deviceType, "device name 3")); diff --git a/dom/media/gtest/TestCDMStorage.cpp b/dom/media/gtest/TestCDMStorage.cpp index 566bc20f9e19..e4d68ff8268d 100644 --- a/dom/media/gtest/TestCDMStorage.cpp +++ b/dom/media/gtest/TestCDMStorage.cpp @@ -69,7 +69,7 @@ static nsresult EnumerateCDMStorageDir(const nsACString& aDir, T&& aDirIter) { } // $profileDir/gmp/$platform/gmp-fake/ - rv = path->Append(NS_LITERAL_STRING("gmp-fake")); + rv = path->Append(u"gmp-fake"_ns); if (NS_FAILED(rv)) { return rv; } @@ -263,9 +263,8 @@ static nsCString GetNodeId(const nsAString& aOrigin, // We rely on the fact that the GetNodeId implementation for // GeckoMediaPluginServiceParent is synchronous. - nsresult rv = - service->GetNodeId(origin, topLevelOrigin, NS_LITERAL_STRING("gmp-fake"), - std::move(callback)); + nsresult rv = service->GetNodeId(origin, topLevelOrigin, u"gmp-fake"_ns, + std::move(callback)); EXPECT_TRUE(NS_SUCCEEDED(rv) && NS_SUCCEEDED(result)); return nodeId; } @@ -313,7 +312,7 @@ class CDMStorageTest { void Update(const nsCString& aMessage) { nsTArray msg; msg.AppendElements(aMessage.get(), aMessage.Length()); - mCDM->UpdateSession(NS_LITERAL_CSTRING("fake-session-id"), 1, msg); + mCDM->UpdateSession("fake-session-id"_ns, 1, msg); } void TestGetNodeId() { @@ -321,8 +320,8 @@ class CDMStorageTest { EXPECT_TRUE(IsCDMStorageIsEmpty()); - const nsString origin1 = NS_LITERAL_STRING("http://example1.com"); - const nsString origin2 = NS_LITERAL_STRING("http://example2.org"); + const nsString origin1 = u"http://example1.com"_ns; + const nsString origin2 = u"http://example2.org"_ns; nsCString PBnodeId1 = GetNodeId(origin1, origin2, true); nsCString PBnodeId2 = GetNodeId(origin1, origin2, true); @@ -362,8 +361,8 @@ class CDMStorageTest { // Once we clear storage, the node ids generated for the same origin-pair // should be different. - const nsString origin1 = NS_LITERAL_STRING("http://example1.com"); - const nsString origin2 = NS_LITERAL_STRING("http://example2.org"); + const nsString origin1 = u"http://example1.com"_ns; + const nsString origin2 = u"http://example2.org"_ns; nsCString nodeId3 = GetNodeId(origin1, origin2, false); EXPECT_TRUE(!aNodeId1.Equals(nodeId3)); @@ -381,9 +380,9 @@ class CDMStorageTest { void CreateDecryptor(const nsAString& aOrigin, const nsAString& aTopLevelOrigin, bool aInPBMode, nsTArray&& aUpdates) { - CreateDecryptor(GetNodeId(aOrigin, aTopLevelOrigin, - NS_LITERAL_STRING("gmp-fake"), aInPBMode), - std::move(aUpdates)); + CreateDecryptor( + GetNodeId(aOrigin, aTopLevelOrigin, u"gmp-fake"_ns, aInPBMode), + std::move(aUpdates)); } void CreateDecryptor(const NodeId& aNodeId, nsTArray&& aUpdates) { @@ -392,7 +391,7 @@ class CDMStorageTest { EXPECT_TRUE(service); nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("fake")); + tags.AppendElement("fake"_ns); RefPtr self = this; RefPtr promise = @@ -431,13 +430,12 @@ class CDMStorageTest { // Send a message to the fake GMP for it to run its own tests internally. // It sends us a "test-storage complete" message when its passed, or // some other message if its tests fail. - Expect(NS_LITERAL_CSTRING("test-storage complete"), + Expect("test-storage complete"_ns, NewRunnableMethod("CDMStorageTest::SetFinished", this, &CDMStorageTest::SetFinished)); - CreateDecryptor(NS_LITERAL_STRING("http://example1.com"), - NS_LITERAL_STRING("http://example2.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example1.com"_ns, u"http://example2.com"_ns, false, + "test-storage"_ns); } /** @@ -454,11 +452,10 @@ class CDMStorageTest { nsCOMPtr r = NewRunnableMethod( "CDMStorageTest::TestForgetThisSite_AnotherSite", this, &CDMStorageTest::TestForgetThisSite_AnotherSite); - Expect(NS_LITERAL_CSTRING("test-storage complete"), r.forget()); + Expect("test-storage complete"_ns, r.forget()); - CreateDecryptor(NS_LITERAL_STRING("http://example1.com"), - NS_LITERAL_STRING("http://example2.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example1.com"_ns, u"http://example2.com"_ns, false, + "test-storage"_ns); } void TestForgetThisSite_AnotherSite() { @@ -468,11 +465,10 @@ class CDMStorageTest { nsCOMPtr r = NewRunnableMethod( "CDMStorageTest::TestForgetThisSite_CollectSiteInfo", this, &CDMStorageTest::TestForgetThisSite_CollectSiteInfo); - Expect(NS_LITERAL_CSTRING("test-storage complete"), r.forget()); + Expect("test-storage complete"_ns, r.forget()); - CreateDecryptor(NS_LITERAL_STRING("http://example3.com"), - NS_LITERAL_STRING("http://example4.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example3.com"_ns, u"http://example4.com"_ns, false, + "test-storage"_ns); } struct NodeInfo { @@ -504,10 +500,9 @@ class CDMStorageTest { mozilla::OriginAttributesPattern pattern; UniquePtr siteInfo( - new NodeInfo(NS_LITERAL_CSTRING("http://example1.com"), pattern)); + new NodeInfo("http://example1.com"_ns, pattern)); // Collect nodeIds that are expected to remain for later comparison. - EnumerateCDMStorageDir(NS_LITERAL_CSTRING("id"), - NodeIdCollector(siteInfo.get())); + EnumerateCDMStorageDir("id"_ns, NodeIdCollector(siteInfo.get())); // Invoke "Forget this site" on the main thread. SchedulerGroup::Dispatch( TaskCategory::Other, @@ -574,12 +569,11 @@ class CDMStorageTest { }; void TestForgetThisSite_Verify(UniquePtr&& aSiteInfo) { - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("id"), - NodeIdVerifier(aSiteInfo.get())); + nsresult rv = + EnumerateCDMStorageDir("id"_ns, NodeIdVerifier(aSiteInfo.get())); EXPECT_TRUE(NS_SUCCEEDED(rv)); - rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("storage"), - StorageVerifier(aSiteInfo.get())); + rv = EnumerateCDMStorageDir("storage"_ns, StorageVerifier(aSiteInfo.get())); EXPECT_TRUE(NS_SUCCEEDED(rv)); } @@ -598,11 +592,10 @@ class CDMStorageTest { nsCOMPtr r = NewRunnableMethod("CDMStorageTest::TestClearRecentHistory1_Clear", this, &CDMStorageTest::TestClearRecentHistory1_Clear); - Expect(NS_LITERAL_CSTRING("test-storage complete"), r.forget()); + Expect("test-storage complete"_ns, r.forget()); - CreateDecryptor(NS_LITERAL_STRING("http://example1.com"), - NS_LITERAL_STRING("http://example2.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example1.com"_ns, u"http://example2.com"_ns, false, + "test-storage"_ns); } /** @@ -620,11 +613,10 @@ class CDMStorageTest { nsCOMPtr r = NewRunnableMethod("CDMStorageTest::TestClearRecentHistory2_Clear", this, &CDMStorageTest::TestClearRecentHistory2_Clear); - Expect(NS_LITERAL_CSTRING("test-storage complete"), r.forget()); + Expect("test-storage complete"_ns, r.forget()); - CreateDecryptor(NS_LITERAL_STRING("http://example1.com"), - NS_LITERAL_STRING("http://example2.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example1.com"_ns, u"http://example2.com"_ns, false, + "test-storage"_ns); } /** @@ -642,11 +634,10 @@ class CDMStorageTest { nsCOMPtr r = NewRunnableMethod("CDMStorageTest::TestClearRecentHistory3_Clear", this, &CDMStorageTest::TestClearRecentHistory3_Clear); - Expect(NS_LITERAL_CSTRING("test-storage complete"), r.forget()); + Expect("test-storage complete"_ns, r.forget()); - CreateDecryptor(NS_LITERAL_STRING("http://example1.com"), - NS_LITERAL_STRING("http://example2.com"), false, - NS_LITERAL_CSTRING("test-storage")); + CreateDecryptor(u"http://example1.com"_ns, u"http://example2.com"_ns, false, + "test-storage"_ns); } class MaxMTimeFinder { @@ -668,7 +659,7 @@ class CDMStorageTest { void TestClearRecentHistory1_Clear() { MaxMTimeFinder f; - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("id"), f); + nsresult rv = EnumerateCDMStorageDir("id"_ns, f); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr r = NewRunnableMethod( @@ -680,7 +671,7 @@ class CDMStorageTest { void TestClearRecentHistory2_Clear() { MaxMTimeFinder f; - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("storage"), f); + nsresult rv = EnumerateCDMStorageDir("storage"_ns, f); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr r = NewRunnableMethod( @@ -692,7 +683,7 @@ class CDMStorageTest { void TestClearRecentHistory3_Clear() { MaxMTimeFinder f; - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("storage"), f); + nsresult rv = EnumerateCDMStorageDir("storage"_ns, f); EXPECT_TRUE(NS_SUCCEEDED(rv)); nsCOMPtr r = NewRunnableMethod( @@ -714,13 +705,13 @@ class CDMStorageTest { void TestClearRecentHistory_CheckEmpty() { FileCounter c1; - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("id"), c1); + nsresult rv = EnumerateCDMStorageDir("id"_ns, c1); EXPECT_TRUE(NS_SUCCEEDED(rv)); // There should be no files under $profileDir/gmp/$platform/gmp-fake/id/ EXPECT_EQ(c1.GetCount(), 0); FileCounter c2; - rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("storage"), c2); + rv = EnumerateCDMStorageDir("storage"_ns, c2); EXPECT_TRUE(NS_SUCCEEDED(rv)); // There should be no files under // $profileDir/gmp/$platform/gmp-fake/storage/ @@ -731,14 +722,14 @@ class CDMStorageTest { void TestClearRecentHistory_CheckNonEmpty() { FileCounter c1; - nsresult rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("id"), c1); + nsresult rv = EnumerateCDMStorageDir("id"_ns, c1); EXPECT_TRUE(NS_SUCCEEDED(rv)); // There should be one directory under // $profileDir/gmp/$platform/gmp-fake/id/ EXPECT_EQ(c1.GetCount(), 1); FileCounter c2; - rv = EnumerateCDMStorageDir(NS_LITERAL_CSTRING("storage"), c2); + rv = EnumerateCDMStorageDir("storage"_ns, c2); EXPECT_TRUE(NS_SUCCEEDED(rv)); // There should be one directory under // $profileDir/gmp/$platform/gmp-fake/storage/ @@ -767,8 +758,8 @@ class CDMStorageTest { // Open decryptor on one, origin, write a record, and test that that // record can't be read on another origin. - CreateDecryptor(NS_LITERAL_STRING("http://example3.com"), - NS_LITERAL_STRING("http://example4.com"), false, update); + CreateDecryptor(u"http://example3.com"_ns, u"http://example4.com"_ns, false, + update); } void TestCrossOriginStorage_RecordStoredContinuation() { @@ -776,14 +767,13 @@ class CDMStorageTest { // and try to read the record. Shutdown(); - Expect(NS_LITERAL_CSTRING( + Expect(nsLiteralCString( "retrieve crossOriginTestRecordId succeeded (length 0 bytes)"), NewRunnableMethod("CDMStorageTest::SetFinished", this, &CDMStorageTest::SetFinished)); - CreateDecryptor(NS_LITERAL_STRING("http://example5.com"), - NS_LITERAL_STRING("http://example6.com"), false, - NS_LITERAL_CSTRING("retrieve crossOriginTestRecordId")); + CreateDecryptor(u"http://example5.com"_ns, u"http://example6.com"_ns, false, + "retrieve crossOriginTestRecordId"_ns); } void TestPBStorage() { @@ -799,49 +789,45 @@ class CDMStorageTest { // open another, and test that record can be read, close decryptor, // then send pb-last-context-closed notification, then open decryptor // and check that it can't read that data; it should have been purged. - CreateDecryptor(NS_LITERAL_STRING("http://pb1.com"), - NS_LITERAL_STRING("http://pb2.com"), true, - NS_LITERAL_CSTRING("store pbdata test-pb-data")); + CreateDecryptor(u"http://pb1.com"_ns, u"http://pb2.com"_ns, true, + "store pbdata test-pb-data"_ns); } void TestPBStorage_RecordStoredContinuation() { Shutdown(); Expect( - NS_LITERAL_CSTRING("retrieve pbdata succeeded (length 12 bytes)"), + "retrieve pbdata succeeded (length 12 bytes)"_ns, NewRunnableMethod( "CDMStorageTest::TestPBStorage_RecordRetrievedContinuation", this, &CDMStorageTest::TestPBStorage_RecordRetrievedContinuation)); - CreateDecryptor(NS_LITERAL_STRING("http://pb1.com"), - NS_LITERAL_STRING("http://pb2.com"), true, - NS_LITERAL_CSTRING("retrieve pbdata")); + CreateDecryptor(u"http://pb1.com"_ns, u"http://pb2.com"_ns, true, + "retrieve pbdata"_ns); } void TestPBStorage_RecordRetrievedContinuation() { Shutdown(); SimulatePBModeExit(); - Expect(NS_LITERAL_CSTRING("retrieve pbdata succeeded (length 0 bytes)"), + Expect("retrieve pbdata succeeded (length 0 bytes)"_ns, NewRunnableMethod("CDMStorageTest::SetFinished", this, &CDMStorageTest::SetFinished)); - CreateDecryptor(NS_LITERAL_STRING("http://pb1.com"), - NS_LITERAL_STRING("http://pb2.com"), true, - NS_LITERAL_CSTRING("retrieve pbdata")); + CreateDecryptor(u"http://pb1.com"_ns, u"http://pb2.com"_ns, true, + "retrieve pbdata"_ns); } #if defined(XP_WIN) void TestOutputProtection() { Shutdown(); - Expect(NS_LITERAL_CSTRING("OP tests completed"), + Expect("OP tests completed"_ns, NewRunnableMethod("CDMStorageTest::SetFinished", this, &CDMStorageTest::SetFinished)); - CreateDecryptor(NS_LITERAL_STRING("http://example15.com"), - NS_LITERAL_STRING("http://example16.com"), false, - NS_LITERAL_CSTRING("test-op-apis")); + CreateDecryptor(u"http://example15.com"_ns, u"http://example16.com"_ns, + false, "test-op-apis"_ns); } #endif @@ -896,8 +882,7 @@ class CDMStorageTest { update.Append(longRecordName); update.AppendLiteral(" "); update.Append(data); - CreateDecryptor(NS_LITERAL_STRING("http://fuz.com"), - NS_LITERAL_STRING("http://baz.com"), false, update); + CreateDecryptor(u"http://fuz.com"_ns, u"http://baz.com"_ns, false, update); } void Expect(const nsCString& aMessage, diff --git a/dom/media/gtest/TestDecoderBenchmark.cpp b/dom/media/gtest/TestDecoderBenchmark.cpp index 81cf6dd58445..85091a49468f 100644 --- a/dom/media/gtest/TestDecoderBenchmark.cpp +++ b/dom/media/gtest/TestDecoderBenchmark.cpp @@ -14,57 +14,53 @@ using namespace mozilla; TEST(DecoderBenchmark, CreateKey) { - DecoderBenchmarkInfo info{NS_LITERAL_CSTRING("video/av1"), 1, 1, 1, 8}; + DecoderBenchmarkInfo info{"video/av1"_ns, 1, 1, 1, 8}; EXPECT_EQ(KeyUtil::CreateKey(info), - NS_LITERAL_CSTRING("ResolutionLevel0-FrameRateLevel0-8bit")) + "ResolutionLevel0-FrameRateLevel0-8bit"_ns) << "Min level"; - DecoderBenchmarkInfo info1{NS_LITERAL_CSTRING("video/av1"), 5000, 5000, 100, - 8}; + DecoderBenchmarkInfo info1{"video/av1"_ns, 5000, 5000, 100, 8}; EXPECT_EQ(KeyUtil::CreateKey(info1), - NS_LITERAL_CSTRING("ResolutionLevel7-FrameRateLevel4-8bit")) + "ResolutionLevel7-FrameRateLevel4-8bit"_ns) << "Max level"; - DecoderBenchmarkInfo info2{NS_LITERAL_CSTRING("video/av1"), 854, 480, 30, 8}; + DecoderBenchmarkInfo info2{"video/av1"_ns, 854, 480, 30, 8}; EXPECT_EQ(KeyUtil::CreateKey(info2), - NS_LITERAL_CSTRING("ResolutionLevel3-FrameRateLevel2-8bit")) + "ResolutionLevel3-FrameRateLevel2-8bit"_ns) << "On the top of 4th resolution level"; - DecoderBenchmarkInfo info3{NS_LITERAL_CSTRING("video/av1"), 1270, 710, 24, 8}; + DecoderBenchmarkInfo info3{"video/av1"_ns, 1270, 710, 24, 8}; EXPECT_EQ(KeyUtil::CreateKey(info3), - NS_LITERAL_CSTRING("ResolutionLevel4-FrameRateLevel1-8bit")) + "ResolutionLevel4-FrameRateLevel1-8bit"_ns) << "Closer to 5th resolution level - bellow"; - DecoderBenchmarkInfo info4{NS_LITERAL_CSTRING("video/av1"), 1290, 730, 24, 8}; + DecoderBenchmarkInfo info4{"video/av1"_ns, 1290, 730, 24, 8}; EXPECT_EQ(KeyUtil::CreateKey(info4), - NS_LITERAL_CSTRING("ResolutionLevel4-FrameRateLevel1-8bit")) + "ResolutionLevel4-FrameRateLevel1-8bit"_ns) << "Closer to 5th resolution level - above"; - DecoderBenchmarkInfo info5{NS_LITERAL_CSTRING("video/av1"), 854, 480, 20, 8}; + DecoderBenchmarkInfo info5{"video/av1"_ns, 854, 480, 20, 8}; EXPECT_EQ(KeyUtil::CreateKey(info5), - NS_LITERAL_CSTRING("ResolutionLevel3-FrameRateLevel1-8bit")) + "ResolutionLevel3-FrameRateLevel1-8bit"_ns) << "Closer to 2nd frame rate level - bellow"; - DecoderBenchmarkInfo info6{NS_LITERAL_CSTRING("video/av1"), 854, 480, 26, 8}; + DecoderBenchmarkInfo info6{"video/av1"_ns, 854, 480, 26, 8}; EXPECT_EQ(KeyUtil::CreateKey(info6), - NS_LITERAL_CSTRING("ResolutionLevel3-FrameRateLevel1-8bit")) + "ResolutionLevel3-FrameRateLevel1-8bit"_ns) << "Closer to 2nd frame rate level - above"; - DecoderBenchmarkInfo info7{NS_LITERAL_CSTRING("video/av1"), 1280, 720, 24, - 10}; + DecoderBenchmarkInfo info7{"video/av1"_ns, 1280, 720, 24, 10}; EXPECT_EQ(KeyUtil::CreateKey(info7), - NS_LITERAL_CSTRING("ResolutionLevel4-FrameRateLevel1-non8bit")) + "ResolutionLevel4-FrameRateLevel1-non8bit"_ns) << "Bit depth 10 bits"; - DecoderBenchmarkInfo info8{NS_LITERAL_CSTRING("video/av1"), 1280, 720, 24, - 12}; + DecoderBenchmarkInfo info8{"video/av1"_ns, 1280, 720, 24, 12}; EXPECT_EQ(KeyUtil::CreateKey(info8), - NS_LITERAL_CSTRING("ResolutionLevel4-FrameRateLevel1-non8bit")) + "ResolutionLevel4-FrameRateLevel1-non8bit"_ns) << "Bit depth 12 bits"; - DecoderBenchmarkInfo info9{NS_LITERAL_CSTRING("video/av1"), 1280, 720, 24, - 16}; + DecoderBenchmarkInfo info9{"video/av1"_ns, 1280, 720, 24, 16}; EXPECT_EQ(KeyUtil::CreateKey(info9), - NS_LITERAL_CSTRING("ResolutionLevel4-FrameRateLevel1-non8bit")) + "ResolutionLevel4-FrameRateLevel1-non8bit"_ns) << "Bit depth 16 bits"; } diff --git a/dom/media/gtest/TestGMPCrossOrigin.cpp b/dom/media/gtest/TestGMPCrossOrigin.cpp index 34d7ec984a35..052e59d4cb24 100644 --- a/dom/media/gtest/TestGMPCrossOrigin.cpp +++ b/dom/media/gtest/TestGMPCrossOrigin.cpp @@ -64,8 +64,8 @@ class RunTestGMPVideoCodec : public Base { static nsresult Get(const nsACString& aNodeId, UniquePtr&& aCallback) { nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); - tags.AppendElement(NS_LITERAL_CSTRING("fake")); + tags.AppendElement("h264"_ns); + tags.AppendElement("fake"_ns); RefPtr service = GeckoMediaPluginService::GetGeckoMediaPluginService(); @@ -83,15 +83,15 @@ typedef RunTestGMPVideoCodec @@ -161,23 +161,19 @@ typedef RunTestGMPCrossOrigin RunTestGMPVideoEncoderCrossOrigin; void GMPTestRunner::RunTestGMPCrossOrigin1(GMPTestMonitor& aMonitor) { - RunTestGMPVideoDecoderCrossOrigin::Run( - aMonitor, NS_LITERAL_CSTRING("origin1"), NS_LITERAL_CSTRING("origin2")); + RunTestGMPVideoDecoderCrossOrigin::Run(aMonitor, "origin1"_ns, "origin2"_ns); } void GMPTestRunner::RunTestGMPCrossOrigin2(GMPTestMonitor& aMonitor) { - RunTestGMPVideoEncoderCrossOrigin::Run( - aMonitor, NS_LITERAL_CSTRING("origin1"), NS_LITERAL_CSTRING("origin2")); + RunTestGMPVideoEncoderCrossOrigin::Run(aMonitor, "origin1"_ns, "origin2"_ns); } void GMPTestRunner::RunTestGMPCrossOrigin3(GMPTestMonitor& aMonitor) { - RunTestGMPVideoDecoderCrossOrigin::Run( - aMonitor, NS_LITERAL_CSTRING("origin1"), NS_LITERAL_CSTRING("origin1")); + RunTestGMPVideoDecoderCrossOrigin::Run(aMonitor, "origin1"_ns, "origin1"_ns); } void GMPTestRunner::RunTestGMPCrossOrigin4(GMPTestMonitor& aMonitor) { - RunTestGMPVideoEncoderCrossOrigin::Run( - aMonitor, NS_LITERAL_CSTRING("origin1"), NS_LITERAL_CSTRING("origin1")); + RunTestGMPVideoEncoderCrossOrigin::Run(aMonitor, "origin1"_ns, "origin1"_ns); } void GMPTestRunner::DoTest( diff --git a/dom/media/gtest/TestGMPRemoveAndDelete.cpp b/dom/media/gtest/TestGMPRemoveAndDelete.cpp index 93049585fff1..291f8f3624b2 100644 --- a/dom/media/gtest/TestGMPRemoveAndDelete.cpp +++ b/dom/media/gtest/TestGMPRemoveAndDelete.cpp @@ -17,9 +17,9 @@ #include "GMPUtils.h" #include "mozilla/StaticPtr.h" -#define GMP_DIR_NAME NS_LITERAL_STRING("gmp-fakeopenh264") -#define GMP_OLD_VERSION NS_LITERAL_STRING("1.0") -#define GMP_NEW_VERSION NS_LITERAL_STRING("1.1") +#define GMP_DIR_NAME u"gmp-fakeopenh264"_ns +#define GMP_OLD_VERSION u"1.0"_ns +#define GMP_NEW_VERSION u"1.1"_ns #define GMP_DELETED_TOPIC "gmp-directory-deleted" @@ -135,7 +135,7 @@ TEST(GeckoMediaPlugins, RemoveAndDeleteForcedInUse) RefPtr test(new GMPRemoveTest()); test->Setup(); - EXPECT_TRUE(test->CreateVideoDecoder(NS_LITERAL_CSTRING("thisOrigin"))); + EXPECT_TRUE(test->CreateVideoDecoder("thisOrigin"_ns)); // Test that we can decode a frame. GMPErr err = test->Decode(); @@ -145,7 +145,7 @@ TEST(GeckoMediaPlugins, RemoveAndDeleteForcedInUse) test->Wait(); // Test that the VideoDecoder is no longer available. - EXPECT_FALSE(test->CreateVideoDecoder(NS_LITERAL_CSTRING("thisOrigin"))); + EXPECT_FALSE(test->CreateVideoDecoder("thisOrigin"_ns)); // Test that we were notified of the plugin's destruction. EXPECT_TRUE(test->IsTerminated()); @@ -160,7 +160,7 @@ TEST(GeckoMediaPlugins, RemoveAndDeleteDeferredInUse) RefPtr test(new GMPRemoveTest()); test->Setup(); - EXPECT_TRUE(test->CreateVideoDecoder(NS_LITERAL_CSTRING("thisOrigin"))); + EXPECT_TRUE(test->CreateVideoDecoder("thisOrigin"_ns)); // Make sure decoding works before we do anything. GMPErr err = test->Decode(); @@ -173,7 +173,7 @@ TEST(GeckoMediaPlugins, RemoveAndDeleteDeferredInUse) EXPECT_EQ(err, GMPNoErr); // Test that this origin is still able to fetch the video decoder. - EXPECT_TRUE(test->CreateVideoDecoder(NS_LITERAL_CSTRING("thisOrigin"))); + EXPECT_TRUE(test->CreateVideoDecoder("thisOrigin"_ns)); test->CloseVideoDecoder(); test->Wait(); @@ -284,8 +284,8 @@ void GMPRemoveTest::gmp_GetVideoDecoder(nsCString aNodeId, GMPVideoDecoderProxy** aOutDecoder, GMPVideoHost** aOutHost) { nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); - tags.AppendElement(NS_LITERAL_CSTRING("fake")); + tags.AppendElement("h264"_ns); + tags.AppendElement("fake"_ns); class Callback : public GetGMPVideoDecoderCallback { public: diff --git a/dom/media/gtest/TestGroupId.cpp b/dom/media/gtest/TestGroupId.cpp index 123c9384cd2a..58eb34a76ef6 100644 --- a/dom/media/gtest/TestGroupId.cpp +++ b/dom/media/gtest/TestGroupId.cpp @@ -47,10 +47,10 @@ class MockMediaEngineSource : public MediaEngineSource { RefPtr MakeAudioDeviceInfo(const nsString aName) { return MakeRefPtr( - nullptr, aName, NS_LITERAL_STRING("GroupId"), NS_LITERAL_STRING("Vendor"), - AudioDeviceInfo::TYPE_OUTPUT, AudioDeviceInfo::STATE_ENABLED, - AudioDeviceInfo::PREF_NONE, AudioDeviceInfo::FMT_F32LE, - AudioDeviceInfo::FMT_F32LE, 2u, 44100u, 44100u, 44100u, 0, 0); + nullptr, aName, u"GroupId"_ns, u"Vendor"_ns, AudioDeviceInfo::TYPE_OUTPUT, + AudioDeviceInfo::STATE_ENABLED, AudioDeviceInfo::PREF_NONE, + AudioDeviceInfo::FMT_F32LE, AudioDeviceInfo::FMT_F32LE, 2u, 44100u, + 44100u, 44100u, 0, 0); } RefPtr MakeCameraDevice(const nsString& aName, @@ -59,8 +59,7 @@ RefPtr MakeCameraDevice(const nsString& aName, EXPECT_CALL(*v, GetMediaSource()) .WillRepeatedly(Return(dom::MediaSourceEnum::Camera)); - return MakeRefPtr(v, aName, NS_LITERAL_STRING(""), aGroupId, - NS_LITERAL_STRING("")); + return MakeRefPtr(v, aName, u""_ns, aGroupId, u""_ns); } RefPtr MakeMicDevice(const nsString& aName, @@ -69,15 +68,13 @@ RefPtr MakeMicDevice(const nsString& aName, EXPECT_CALL(*a, GetMediaSource()) .WillRepeatedly(Return(dom::MediaSourceEnum::Microphone)); - return MakeRefPtr(a, aName, NS_LITERAL_STRING(""), aGroupId, - NS_LITERAL_STRING("")); + return MakeRefPtr(a, aName, u""_ns, aGroupId, u""_ns); } RefPtr MakeSpeakerDevice(const nsString& aName, const nsString& aGroupId) { - return MakeRefPtr(MakeAudioDeviceInfo(aName), - NS_LITERAL_STRING("ID"), aGroupId, - NS_LITERAL_STRING("RawID")); + return MakeRefPtr(MakeAudioDeviceInfo(aName), u"ID"_ns, aGroupId, + u"RawID"_ns); } /* Verify that when an audio input device name contains the video input device @@ -89,11 +86,10 @@ TEST(TestGroupId, MatchInput_PartOfName) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); - auto mic = MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId")); + auto mic = + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns); devices.AppendElement(mic); audios.AppendElement(mic); @@ -112,11 +108,9 @@ TEST(TestGroupId, MatchInput_FullName) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); - auto mic = MakeMicDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Mic-Model-GroupId")); + auto mic = MakeMicDevice(u"Vendor Model"_ns, u"Mic-Model-GroupId"_ns); devices.AppendElement(mic); audios.AppendElement(mic); @@ -133,12 +127,12 @@ TEST(TestGroupId, NoMatchInput) MediaManager::MediaDeviceSet devices; MediaManager::MediaDeviceSet audios; - nsString Cam_Model_GroupId = NS_LITERAL_STRING("Cam-Model-GroupId"); + nsString Cam_Model_GroupId = u"Cam-Model-GroupId"_ns; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), Cam_Model_GroupId)); + MakeCameraDevice(u"Vendor Model"_ns, Cam_Model_GroupId)); - audios.AppendElement(MakeMicDevice(NS_LITERAL_STRING("Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + audios.AppendElement( + MakeMicDevice(u"Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -156,23 +150,19 @@ TEST(TestGroupId, NoMatch_TwoIdenticalDevices) MediaManager::MediaDeviceSet devices; MediaManager::MediaDeviceSet audios; - nsString Cam_Model_GroupId = NS_LITERAL_STRING("Cam-Model-GroupId"); + nsString Cam_Model_GroupId = u"Cam-Model-GroupId"_ns; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), Cam_Model_GroupId)); + MakeCameraDevice(u"Vendor Model"_ns, Cam_Model_GroupId)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -193,20 +183,17 @@ TEST(TestGroupId, Match_TwoIdenticalInputsMatchOutput) MediaManager::MediaDeviceSet devices; MediaManager::MediaDeviceSet audios; - nsString Cam_Model_GroupId = NS_LITERAL_STRING("Cam-Model-GroupId"); + nsString Cam_Model_GroupId = u"Cam-Model-GroupId"_ns; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), Cam_Model_GroupId)); + MakeCameraDevice(u"Vendor Model"_ns, Cam_Model_GroupId)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -222,29 +209,23 @@ TEST(TestGroupId, NoMatch_ThreeIdenticalDevices) MediaManager::MediaDeviceSet devices; MediaManager::MediaDeviceSet audios; - nsString Cam_Model_GroupId = NS_LITERAL_STRING("Cam-Model-GroupId"); + nsString Cam_Model_GroupId = u"Cam-Model-GroupId"_ns; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), Cam_Model_GroupId)); + MakeCameraDevice(u"Vendor Model"_ns, Cam_Model_GroupId)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeMicDevice(u"Vendor Model Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); - audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -265,15 +246,13 @@ TEST(TestGroupId, MatchOutput) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); - - audios.AppendElement(MakeMicDevice(NS_LITERAL_STRING("Mic Analog Stereo"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model Analog Stereo"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); + MakeMicDevice(u"Mic Analog Stereo"_ns, u"Mic-Model-GroupId"_ns)); + + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model Analog Stereo"_ns, + u"Speaker-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -290,15 +269,13 @@ TEST(TestGroupId, InputOutputSameName) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); - audios.AppendElement(MakeMicDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Mic-Model-GroupId"))); + audios.AppendElement( + MakeMicDevice(u"Vendor Model"_ns, u"Mic-Model-GroupId"_ns)); audios.AppendElement( - MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Speaker-Model-GroupId"))); + MakeSpeakerDevice(u"Vendor Model"_ns, u"Speaker-Model-GroupId"_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -315,11 +292,9 @@ TEST(TestGroupId, InputEmptyGroupId) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); - audios.AppendElement( - MakeMicDevice(NS_LITERAL_STRING("Vendor Model"), NS_LITERAL_STRING(""))); + audios.AppendElement(MakeMicDevice(u"Vendor Model"_ns, u""_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); @@ -336,11 +311,9 @@ TEST(TestGroupId, OutputEmptyGroupId) MediaManager::MediaDeviceSet audios; devices.AppendElement( - MakeCameraDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING("Cam-Model-GroupId"))); + MakeCameraDevice(u"Vendor Model"_ns, u"Cam-Model-GroupId"_ns)); - audios.AppendElement(MakeSpeakerDevice(NS_LITERAL_STRING("Vendor Model"), - NS_LITERAL_STRING(""))); + audios.AppendElement(MakeSpeakerDevice(u"Vendor Model"_ns, u""_ns)); MediaManager::GuessVideoDeviceGroupIDs(devices, audios); diff --git a/dom/media/gtest/TestMediaDataEncoder.cpp b/dom/media/gtest/TestMediaDataEncoder.cpp index 6b5a3d08218f..708fa9d30f3e 100644 --- a/dom/media/gtest/TestMediaDataEncoder.cpp +++ b/dom/media/gtest/TestMediaDataEncoder.cpp @@ -18,12 +18,12 @@ #include -#define SKIP_IF_NOT_SUPPORTED(mimeType) \ - do { \ - RefPtr f(new PEMFactory()); \ - if (!f->SupportsMimeType(NS_LITERAL_CSTRING(mimeType))) { \ - return; \ - } \ +#define SKIP_IF_NOT_SUPPORTED(mimeType) \ + do { \ + RefPtr f(new PEMFactory()); \ + if (!f->SupportsMimeType(nsLiteralCString(mimeType))) { \ + return; \ + } \ } while (0) #define BLOCK_SIZE 64 @@ -141,12 +141,12 @@ static already_AddRefed CreateH264Encoder( MediaDataEncoder::H264Specific::ProfileLevel::BaselineAutoLevel))) { RefPtr f(new PEMFactory()); - if (!f->SupportsMimeType(NS_LITERAL_CSTRING(VIDEO_MP4))) { + if (!f->SupportsMimeType(nsLiteralCString(VIDEO_MP4))) { return nullptr; } VideoInfo videoInfo(WIDTH, HEIGHT); - videoInfo.mMimeType = NS_LITERAL_CSTRING(VIDEO_MP4); + videoInfo.mMimeType = nsLiteralCString(VIDEO_MP4); const RefPtr taskQueue( new TaskQueue(GetMediaThreadPool(MediaThreadType::PLAYBACK))); diff --git a/dom/media/gtest/TestMediaMIMETypes.cpp b/dom/media/gtest/TestMediaMIMETypes.cpp index dbf531d40162..d36e3bf586ab 100644 --- a/dom/media/gtest/TestMediaMIMETypes.cpp +++ b/dom/media/gtest/TestMediaMIMETypes.cpp @@ -86,10 +86,10 @@ TEST(MediaMIMETypes, MediaCodecs) MediaCodecs empty(""); EXPECT_TRUE(empty.IsEmpty()); EXPECT_TRUE(empty.AsString().EqualsLiteral("")); - EXPECT_FALSE(empty.Contains(NS_LITERAL_STRING(""))); - EXPECT_FALSE(empty.Contains(NS_LITERAL_STRING("c1"))); - EXPECT_FALSE(empty.ContainsPrefix(NS_LITERAL_STRING(""))); - EXPECT_FALSE(empty.ContainsPrefix(NS_LITERAL_STRING("c1"))); + EXPECT_FALSE(empty.Contains(u""_ns)); + EXPECT_FALSE(empty.Contains(u"c1"_ns)); + EXPECT_FALSE(empty.ContainsPrefix(u""_ns)); + EXPECT_FALSE(empty.ContainsPrefix(u"c1"_ns)); int iterations = 0; for (const auto& codec : empty.Range()) { ++iterations; @@ -100,11 +100,11 @@ TEST(MediaMIMETypes, MediaCodecs) MediaCodecs space(" "); EXPECT_FALSE(space.IsEmpty()); EXPECT_TRUE(space.AsString().EqualsLiteral(" ")); - EXPECT_TRUE(space.Contains(NS_LITERAL_STRING(""))); - EXPECT_FALSE(space.Contains(NS_LITERAL_STRING("c1"))); - EXPECT_TRUE(space.ContainsPrefix(NS_LITERAL_STRING(""))); - EXPECT_FALSE(space.ContainsPrefix(NS_LITERAL_STRING("c"))); - EXPECT_FALSE(space.ContainsPrefix(NS_LITERAL_STRING("c1"))); + EXPECT_TRUE(space.Contains(u""_ns)); + EXPECT_FALSE(space.Contains(u"c1"_ns)); + EXPECT_TRUE(space.ContainsPrefix(u""_ns)); + EXPECT_FALSE(space.ContainsPrefix(u"c"_ns)); + EXPECT_FALSE(space.ContainsPrefix(u"c1"_ns)); iterations = 0; for (const auto& codec : space.Range()) { ++iterations; @@ -115,13 +115,13 @@ TEST(MediaMIMETypes, MediaCodecs) MediaCodecs one(" c1 "); EXPECT_FALSE(one.IsEmpty()); EXPECT_TRUE(one.AsString().EqualsLiteral(" c1 ")); - EXPECT_FALSE(one.Contains(NS_LITERAL_STRING(""))); - EXPECT_TRUE(one.Contains(NS_LITERAL_STRING("c1"))); - EXPECT_TRUE(one.ContainsPrefix(NS_LITERAL_STRING(""))); - EXPECT_TRUE(one.ContainsPrefix(NS_LITERAL_STRING("c"))); - EXPECT_TRUE(one.ContainsPrefix(NS_LITERAL_STRING("c1"))); - EXPECT_FALSE(one.ContainsPrefix(NS_LITERAL_STRING("c1x"))); - EXPECT_FALSE(one.ContainsPrefix(NS_LITERAL_STRING("c1 "))); + EXPECT_FALSE(one.Contains(u""_ns)); + EXPECT_TRUE(one.Contains(u"c1"_ns)); + EXPECT_TRUE(one.ContainsPrefix(u""_ns)); + EXPECT_TRUE(one.ContainsPrefix(u"c"_ns)); + EXPECT_TRUE(one.ContainsPrefix(u"c1"_ns)); + EXPECT_FALSE(one.ContainsPrefix(u"c1x"_ns)); + EXPECT_FALSE(one.ContainsPrefix(u"c1 "_ns)); iterations = 0; for (const auto& codec : one.Range()) { ++iterations; @@ -132,16 +132,16 @@ TEST(MediaMIMETypes, MediaCodecs) MediaCodecs two(" c1 , c2 "); EXPECT_FALSE(two.IsEmpty()); EXPECT_TRUE(two.AsString().EqualsLiteral(" c1 , c2 ")); - EXPECT_FALSE(two.Contains(NS_LITERAL_STRING(""))); - EXPECT_TRUE(two.Contains(NS_LITERAL_STRING("c1"))); - EXPECT_TRUE(two.Contains(NS_LITERAL_STRING("c2"))); - EXPECT_TRUE(two.ContainsPrefix(NS_LITERAL_STRING(""))); - EXPECT_TRUE(two.ContainsPrefix(NS_LITERAL_STRING("c"))); - EXPECT_FALSE(two.ContainsPrefix(NS_LITERAL_STRING("1"))); - EXPECT_TRUE(two.ContainsPrefix(NS_LITERAL_STRING("c1"))); - EXPECT_TRUE(two.ContainsPrefix(NS_LITERAL_STRING("c2"))); - EXPECT_FALSE(two.ContainsPrefix(NS_LITERAL_STRING("c1x"))); - EXPECT_FALSE(two.ContainsPrefix(NS_LITERAL_STRING("c2x"))); + EXPECT_FALSE(two.Contains(u""_ns)); + EXPECT_TRUE(two.Contains(u"c1"_ns)); + EXPECT_TRUE(two.Contains(u"c2"_ns)); + EXPECT_TRUE(two.ContainsPrefix(u""_ns)); + EXPECT_TRUE(two.ContainsPrefix(u"c"_ns)); + EXPECT_FALSE(two.ContainsPrefix(u"1"_ns)); + EXPECT_TRUE(two.ContainsPrefix(u"c1"_ns)); + EXPECT_TRUE(two.ContainsPrefix(u"c2"_ns)); + EXPECT_FALSE(two.ContainsPrefix(u"c1x"_ns)); + EXPECT_FALSE(two.ContainsPrefix(u"c2x"_ns)); iterations = 0; for (const auto& codec : two.Range()) { ++iterations; @@ -161,21 +161,21 @@ TEST(MediaMIMETypes, MediaCodecs) // the wide representation from MediaCodecs. MediaCodecs euroSign(" € "); // U+20AC EXPECT_FALSE(euroSign.IsEmpty()); - EXPECT_TRUE(euroSign.AsString().Equals(NS_LITERAL_STRING(" € "))); - EXPECT_FALSE(euroSign.Contains(NS_LITERAL_STRING(""))); - EXPECT_TRUE(euroSign.Contains(NS_LITERAL_STRING("€"))); - EXPECT_FALSE(euroSign.Contains(NS_LITERAL_STRING("€€"))); - EXPECT_TRUE(euroSign.ContainsPrefix(NS_LITERAL_STRING(""))); - EXPECT_TRUE(euroSign.ContainsPrefix(NS_LITERAL_STRING("€"))); + EXPECT_TRUE(euroSign.AsString().Equals(u" € "_ns)); + EXPECT_FALSE(euroSign.Contains(u""_ns)); + EXPECT_TRUE(euroSign.Contains(u"€"_ns)); + EXPECT_FALSE(euroSign.Contains(u"€€"_ns)); + EXPECT_TRUE(euroSign.ContainsPrefix(u""_ns)); + EXPECT_TRUE(euroSign.ContainsPrefix(u"€"_ns)); EXPECT_FALSE(euroSign.ContainsPrefix( - NS_LITERAL_STRING("₭"))); // U+20AD -- ensure second octet is compared + u"₭"_ns)); // U+20AD -- ensure second octet is compared EXPECT_FALSE(euroSign.ContainsPrefix( - NS_LITERAL_STRING("↬"))); // U+21AC -- ensure first octet is compared - EXPECT_FALSE(euroSign.ContainsPrefix(NS_LITERAL_STRING("€ "))); + u"↬"_ns)); // U+21AC -- ensure first octet is compared + EXPECT_FALSE(euroSign.ContainsPrefix(u"€ "_ns)); iterations = 0; for (const auto& codec : euroSign.Range()) { ++iterations; - EXPECT_TRUE(codec.Equals(NS_LITERAL_STRING("€"))); + EXPECT_TRUE(codec.Equals(u"€"_ns)); } EXPECT_EQ(1, iterations); } @@ -266,13 +266,13 @@ TEST(MediaMIMETypes, MediaExtendedMIMEType) EXPECT_FALSE(type->Codecs().IsEmpty()); EXPECT_TRUE(type->Codecs().AsString().EqualsASCII("a,b")); EXPECT_TRUE(type->Codecs() == "a,b"); - EXPECT_TRUE(type->Codecs().Contains(NS_LITERAL_STRING("a"))); - EXPECT_TRUE(type->Codecs().Contains(NS_LITERAL_STRING("b"))); - EXPECT_TRUE(type->Codecs().ContainsPrefix(NS_LITERAL_STRING("a"))); - EXPECT_TRUE(type->Codecs().ContainsPrefix(NS_LITERAL_STRING("b"))); - EXPECT_FALSE(type->Codecs().ContainsPrefix(NS_LITERAL_STRING("ab"))); - EXPECT_FALSE(type->Codecs().ContainsPrefix(NS_LITERAL_STRING("ba"))); - EXPECT_FALSE(type->Codecs().ContainsPrefix(NS_LITERAL_STRING("a,b"))); + EXPECT_TRUE(type->Codecs().Contains(u"a"_ns)); + EXPECT_TRUE(type->Codecs().Contains(u"b"_ns)); + EXPECT_TRUE(type->Codecs().ContainsPrefix(u"a"_ns)); + EXPECT_TRUE(type->Codecs().ContainsPrefix(u"b"_ns)); + EXPECT_FALSE(type->Codecs().ContainsPrefix(u"ab"_ns)); + EXPECT_FALSE(type->Codecs().ContainsPrefix(u"ba"_ns)); + EXPECT_FALSE(type->Codecs().ContainsPrefix(u"a,b"_ns)); EXPECT_TRUE(!!type->GetWidth()); EXPECT_EQ(1024, *type->GetWidth()); EXPECT_TRUE(!!type->GetHeight()); diff --git a/dom/media/gtest/mp4_demuxer/TestParser.cpp b/dom/media/gtest/mp4_demuxer/TestParser.cpp index 6824652f2bf3..df3ce20c1357 100644 --- a/dom/media/gtest/mp4_demuxer/TestParser.cpp +++ b/dom/media/gtest/mp4_demuxer/TestParser.cpp @@ -942,19 +942,19 @@ TEST_F(MP4MetadataTelemetryFixture, Telemetry) { // Clear histograms TelemetryTestHelpers::GetAndClearHistogram( cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING( + nsLiteralCString( "MEDIA_MP4_PARSE_SAMPLE_DESCRIPTION_ENTRIES_HAVE_MULTIPLE_CODECS"), false /* is_keyed */); TelemetryTestHelpers::GetAndClearHistogram( cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING( + nsLiteralCString( "MEDIA_MP4_PARSE_SAMPLE_DESCRIPTION_ENTRIES_HAVE_MULTIPLE_CRYPTO"), false /* is_keyed */); TelemetryTestHelpers::GetAndClearHistogram( cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("MEDIA_MP4_PARSE_NUM_SAMPLE_DESCRIPTION_ENTRIES"), + "MEDIA_MP4_PARSE_NUM_SAMPLE_DESCRIPTION_ENTRIES"_ns, false /* is_keyed */); // The snapshot won't have any data in it until we populate our histograms, so diff --git a/dom/media/imagecapture/CaptureTask.cpp b/dom/media/imagecapture/CaptureTask.cpp index 43bdec0573ed..360d35470c74 100644 --- a/dom/media/imagecapture/CaptureTask.cpp +++ b/dom/media/imagecapture/CaptureTask.cpp @@ -150,7 +150,7 @@ void CaptureTask::NotifyRealtimeTrackData(MediaTrackGraph* aGraph, // Encode image. nsresult rv; - nsAutoString type(NS_LITERAL_STRING("image/jpeg")); + nsAutoString type(u"image/jpeg"_ns); nsAutoString options; rv = dom::ImageEncoder::ExtractDataFromLayersImageAsync( type, options, false, image, false, new EncodeComplete(this)); diff --git a/dom/media/imagecapture/ImageCapture.cpp b/dom/media/imagecapture/ImageCapture.cpp index 17879164fa24..0e71aa5603a9 100644 --- a/dom/media/imagecapture/ImageCapture.cpp +++ b/dom/media/imagecapture/ImageCapture.cpp @@ -154,7 +154,7 @@ nsresult ImageCapture::PostBlobEvent(Blob* aBlob) { init.mData = aBlob; RefPtr blob_event = - BlobEvent::Constructor(this, NS_LITERAL_STRING("photo"), init); + BlobEvent::Constructor(this, u"photo"_ns, init); return DispatchTrustedEvent(blob_event); } @@ -181,8 +181,8 @@ nsresult ImageCapture::PostErrorEvent(uint16_t aErrorCode, nsresult aReason) { init.mCancelable = false; init.mImageCaptureError = error; - RefPtr event = ImageCaptureErrorEvent::Constructor( - this, NS_LITERAL_STRING("error"), init); + RefPtr event = + ImageCaptureErrorEvent::Constructor(this, u"error"_ns, init); return DispatchTrustedEvent(event); } diff --git a/dom/media/ipc/RDDProcessManager.cpp b/dom/media/ipc/RDDProcessManager.cpp index bbd1648f00a5..cff104254a11 100644 --- a/dom/media/ipc/RDDProcessManager.cpp +++ b/dom/media/ipc/RDDProcessManager.cpp @@ -168,8 +168,7 @@ void RDDProcessManager::OnProcessLaunchComplete(RDDProcessHost* aHost) { mQueuedPrefs.Clear(); CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::RDDProcessStatus, - NS_LITERAL_CSTRING("Running")); + CrashReporter::Annotation::RDDProcessStatus, "Running"_ns); } void RDDProcessManager::OnProcessUnexpectedShutdown(RDDProcessHost* aHost) { @@ -221,8 +220,7 @@ void RDDProcessManager::DestroyProcess() { mQueuedPrefs.Clear(); CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::RDDProcessStatus, - NS_LITERAL_CSTRING("Destroyed")); + CrashReporter::Annotation::RDDProcessStatus, "Destroyed"_ns); } bool RDDProcessManager::CreateContentBridge( diff --git a/dom/media/ipc/RemoteMediaDataDecoder.cpp b/dom/media/ipc/RemoteMediaDataDecoder.cpp index 9d84f8a5d92f..f50a54a63f55 100644 --- a/dom/media/ipc/RemoteMediaDataDecoder.cpp +++ b/dom/media/ipc/RemoteMediaDataDecoder.cpp @@ -34,8 +34,7 @@ RefPtr RemoteMediaDataDecoder::Init() { return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_CANCELED, __func__); } - mDescription = - mChild->GetDescriptionName() + NS_LITERAL_CSTRING(" (remote)"); + mDescription = mChild->GetDescriptionName() + " (remote)"_ns; mIsHardwareAccelerated = mChild->IsHardwareAccelerated(mHardwareAcceleratedReason); mConversion = mChild->NeedsConversion(); diff --git a/dom/media/ipc/RemoteMediaDataDecoder.h b/dom/media/ipc/RemoteMediaDataDecoder.h index 1e326917f882..cd7abf8bb861 100644 --- a/dom/media/ipc/RemoteMediaDataDecoder.h +++ b/dom/media/ipc/RemoteMediaDataDecoder.h @@ -54,7 +54,7 @@ class RemoteMediaDataDecoder RefPtr mChild; // Only ever written/modified during decoder initialisation. // As such can be accessed from any threads after that. - nsCString mDescription = NS_LITERAL_CSTRING("RemoteMediaDataDecoder"); + nsCString mDescription = "RemoteMediaDataDecoder"_ns; bool mIsHardwareAccelerated = false; nsCString mHardwareAcceleratedReason; ConversionRequired mConversion = ConversionRequired::kNeedNone; diff --git a/dom/media/mediacapabilities/BenchmarkStorageParent.cpp b/dom/media/mediacapabilities/BenchmarkStorageParent.cpp index fc2078dab523..64ae6ddd4456 100644 --- a/dom/media/mediacapabilities/BenchmarkStorageParent.cpp +++ b/dom/media/mediacapabilities/BenchmarkStorageParent.cpp @@ -109,7 +109,7 @@ IPCResult BenchmarkStorageParent::RecvGet(const nsCString& aDbName, IPCResult BenchmarkStorageParent::RecvCheckVersion(const nsCString& aDbName, int32_t aVersion) { - mStorage->Get(aDbName, NS_LITERAL_CSTRING("Version")) + mStorage->Get(aDbName, "Version"_ns) ->Then( GetCurrentSerialEventTarget(), __func__, [storage = mStorage, aDbName, aVersion](int32_t aResult) { @@ -117,8 +117,7 @@ IPCResult BenchmarkStorageParent::RecvCheckVersion(const nsCString& aDbName, storage->Clear(aDbName)->Then( GetCurrentSerialEventTarget(), __func__, [storage, aDbName, aVersion](bool) { - storage->Put(aDbName, NS_LITERAL_CSTRING("Version"), - aVersion); + storage->Put(aDbName, "Version"_ns, aVersion); }, [](nsresult rv) { /*do nothing*/ }); } diff --git a/dom/media/mediacapabilities/DecoderBenchmark.cpp b/dom/media/mediacapabilities/DecoderBenchmark.cpp index 80172875aa4e..a6bc98c14a2e 100644 --- a/dom/media/mediacapabilities/DecoderBenchmark.cpp +++ b/dom/media/mediacapabilities/DecoderBenchmark.cpp @@ -112,7 +112,7 @@ nsCString KeyUtil::FindLevel(const uint32_t aLevels[], const size_t length, uint32_t aValue) { MOZ_ASSERT(aValue); if (aValue <= aLevels[0]) { - return NS_LITERAL_CSTRING("Level0"); + return "Level0"_ns; } nsAutoCString level("Level"); size_t lastIndex = length - 1; @@ -132,21 +132,21 @@ nsCString KeyUtil::FindLevel(const uint32_t aLevels[], const size_t length, return std::move(level); } MOZ_CRASH("Array is not sorted"); - return NS_LITERAL_CSTRING(""); + return ""_ns; } /* static */ nsCString KeyUtil::BitDepthToStr(uint8_t aBitDepth) { switch (aBitDepth) { case 8: // ColorDepth::COLOR_8 - return NS_LITERAL_CSTRING("-8bit"); + return "-8bit"_ns; case 10: // ColorDepth::COLOR_10 case 12: // ColorDepth::COLOR_12 case 16: // ColorDepth::COLOR_16 - return NS_LITERAL_CSTRING("-non8bit"); + return "-non8bit"_ns; } MOZ_ASSERT_UNREACHABLE("invalid color depth value"); - return NS_LITERAL_CSTRING(""); + return ""_ns; } /* static */ @@ -199,7 +199,7 @@ static nsDataHashtable DecoderVersionTable() { * will be erased. An example of assigning the version number `1` for AV1 * decoder is: * - * decoderVersionTable.Put(NS_LITERAL_CSTRING("video/av1"), 1); + * decoderVersionTable.Put("video/av1"_ns, 1); * * For the decoders not listed here the `CheckVersion` method exits early, to * avoid sending unecessary IPC messages. diff --git a/dom/media/mediacapabilities/KeyValueStorage.cpp b/dom/media/mediacapabilities/KeyValueStorage.cpp index c6fc00fc9543..3fa3c7c43808 100644 --- a/dom/media/mediacapabilities/KeyValueStorage.cpp +++ b/dom/media/mediacapabilities/KeyValueStorage.cpp @@ -54,7 +54,7 @@ RefPtr KeyValueStorage::Init() { } MOZ_ASSERT(profileDir); - rv = profileDir->AppendNative(NS_LITERAL_CSTRING("mediacapabilities")); + rv = profileDir->AppendNative("mediacapabilities"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return GenericPromise::CreateAndReject(rv, __func__); } diff --git a/dom/media/mediacapabilities/MediaCapabilities.cpp b/dom/media/mediacapabilities/MediaCapabilities.cpp index fb1b1a2cb32c..3f3f6285ee2b 100644 --- a/dom/media/mediacapabilities/MediaCapabilities.cpp +++ b/dom/media/mediacapabilities/MediaCapabilities.cpp @@ -82,19 +82,17 @@ static nsCString MediaCapabilitiesInfoToStr( static nsCString MediaDecodingConfigurationToStr( const MediaDecodingConfiguration& aConfig) { nsCString str; - str += NS_LITERAL_CSTRING("["); + str += "["_ns; if (aConfig.mVideo.WasPassed()) { - str += NS_LITERAL_CSTRING("video:") + - VideoConfigurationToStr(&aConfig.mVideo.Value()); + str += "video:"_ns + VideoConfigurationToStr(&aConfig.mVideo.Value()); if (aConfig.mAudio.WasPassed()) { - str += NS_LITERAL_CSTRING(" "); + str += " "_ns; } } if (aConfig.mAudio.WasPassed()) { - str += NS_LITERAL_CSTRING("audio:") + - AudioConfigurationToStr(&aConfig.mAudio.Value()); + str += "audio:"_ns + AudioConfigurationToStr(&aConfig.mAudio.Value()); } - str += NS_LITERAL_CSTRING("]"); + str += "]"_ns; return str; } diff --git a/dom/media/mediacontrol/MediaController.cpp b/dom/media/mediacontrol/MediaController.cpp index c83feee1485a..c0402e5d00df 100644 --- a/dom/media/mediacontrol/MediaController.cpp +++ b/dom/media/mediacontrol/MediaController.cpp @@ -365,7 +365,7 @@ void MediaController::HandleSupportedMediaSessionActionsChanged( mSupportedKeys = newSupportedKeys; mSupportedKeysChangedEvent.Notify(mSupportedKeys); RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("supportedkeyschange"), CanBubble::eYes); + this, u"supportedkeyschange"_ns, CanBubble::eYes); asyncDispatcher->PostDOMEvent(); MediaController_Binding::ClearCachedSupportedKeysValue(this); } diff --git a/dom/media/mediacontrol/MediaStatusManager.cpp b/dom/media/mediacontrol/MediaStatusManager.cpp index 25afc0554d6d..7fa7e9e0f1d6 100644 --- a/dom/media/mediacontrol/MediaStatusManager.cpp +++ b/dom/media/mediacontrol/MediaStatusManager.cpp @@ -215,8 +215,8 @@ nsString MediaStatusManager::GetDefaultFaviconURL() const { #ifdef MOZ_PLACES nsCOMPtr faviconURI; nsresult rv = NS_NewURI(getter_AddRefs(faviconURI), - NS_LITERAL_CSTRING(FAVICON_DEFAULT_URL)); - NS_ENSURE_SUCCESS(rv, NS_LITERAL_STRING("")); + nsLiteralCString(FAVICON_DEFAULT_URL)); + NS_ENSURE_SUCCESS(rv, u""_ns); // Convert URI from `chrome://XXX` to `file://XXX` because we would like to // let OS related frameworks, such as SMTC and MPRIS, handle this URL in order diff --git a/dom/media/mp3/MP3Decoder.cpp b/dom/media/mp3/MP3Decoder.cpp index 994d54e26f97..88aeb0b66b2a 100644 --- a/dom/media/mp3/MP3Decoder.cpp +++ b/dom/media/mp3/MP3Decoder.cpp @@ -13,7 +13,7 @@ namespace mozilla { /* static */ bool MP3Decoder::IsEnabled() { RefPtr platform = new PDMFactory(); - return platform->SupportsMimeType(NS_LITERAL_CSTRING("audio/mpeg"), + return platform->SupportsMimeType("audio/mpeg"_ns, /* DecoderDoctorDiagnostics* */ nullptr); } @@ -37,7 +37,7 @@ nsTArray> MP3Decoder::GetTracksInfo( tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/mpeg"), aType)); + "audio/mpeg"_ns, aType)); return tracks; } diff --git a/dom/media/mp4/DecoderData.cpp b/dom/media/mp4/DecoderData.cpp index 6c551d6cae86..386a51b6cd81 100644 --- a/dom/media/mp4/DecoderData.cpp +++ b/dom/media/mp4/DecoderData.cpp @@ -161,7 +161,7 @@ MediaResult MP4AudioInfo::Update(const Mp4parseTrackInfo* track, Mp4parseByteData codecSpecificConfig = audio->sample_info[0].codec_specific_config; if (codecType == MP4PARSE_CODEC_OPUS) { - mMimeType = NS_LITERAL_CSTRING("audio/opus"); + mMimeType = "audio/opus"_ns; // The Opus decoder expects the container's codec delay or // pre-skip value, in microseconds, as a 64-bit int at the // start of the codec-specific config blob. @@ -175,11 +175,11 @@ MediaResult MP4AudioInfo::Update(const Mp4parseTrackInfo* track, mozilla::OpusDataDecoder::AppendCodecDelay(mCodecSpecificConfig, 0); } } else if (codecType == MP4PARSE_CODEC_AAC) { - mMimeType = NS_LITERAL_CSTRING("audio/mp4a-latm"); + mMimeType = "audio/mp4a-latm"_ns; } else if (codecType == MP4PARSE_CODEC_FLAC) { - mMimeType = NS_LITERAL_CSTRING("audio/flac"); + mMimeType = "audio/flac"_ns; } else if (codecType == MP4PARSE_CODEC_MP3) { - mMimeType = NS_LITERAL_CSTRING("audio/mpeg"); + mMimeType = "audio/mpeg"_ns; } mRate = audio->sample_info[0].sample_rate; @@ -230,13 +230,13 @@ MediaResult MP4VideoInfo::Update(const Mp4parseTrackInfo* track, // ever not hold. E.g. if we need to handle different codecs in a single // track, or if we have different numbers or channels in a single track. if (codecType == MP4PARSE_CODEC_AVC) { - mMimeType = NS_LITERAL_CSTRING("video/avc"); + mMimeType = "video/avc"_ns; } else if (codecType == MP4PARSE_CODEC_VP9) { - mMimeType = NS_LITERAL_CSTRING("video/vp9"); + mMimeType = "video/vp9"_ns; } else if (codecType == MP4PARSE_CODEC_AV1) { - mMimeType = NS_LITERAL_CSTRING("video/av1"); + mMimeType = "video/av1"_ns; } else if (codecType == MP4PARSE_CODEC_MP4V) { - mMimeType = NS_LITERAL_CSTRING("video/mp4v-es"); + mMimeType = "video/mp4v-es"_ns; } mTrackId = track->track_id; mDuration = TimeUnit::FromMicroseconds(track->duration); diff --git a/dom/media/mp4/Index.cpp b/dom/media/mp4/Index.cpp index 768de8a5fcb9..9da7de9869b9 100644 --- a/dom/media/mp4/Index.cpp +++ b/dom/media/mp4/Index.cpp @@ -129,7 +129,7 @@ already_AddRefed SampleIterator::GetNext() { // the init data on the Moof's first sample, to avoid reporting it more // than once per Moof. writer->mCrypto.mInitDatas.AppendElements(currentMoof->mPsshes); - writer->mCrypto.mInitDataType = NS_LITERAL_STRING("cenc"); + writer->mCrypto.mInitDataType = u"cenc"_ns; } } @@ -312,7 +312,7 @@ Result SampleIterator::GetEncryptionScheme() { // entry. // If we encounter this error often, we may consider using the first // sample description entry if the index is out of bounds. - return mozilla::Err(NS_LITERAL_CSTRING( + return mozilla::Err(nsLiteralCString( "Could not determine encryption scheme due to bad index for sample " "description entry.")); } @@ -325,7 +325,7 @@ Result SampleIterator::GetEncryptionScheme() { // The sample description entry says this sample is encrypted, but we // don't have a valid sinf box. This shouldn't happen as the sinf box is // part of the sample description entry. Suggests a malformed file, bail. - return mozilla::Err(NS_LITERAL_CSTRING( + return mozilla::Err(nsLiteralCString( "Could not determine encryption scheme. Sample description entry " "indicates encryption, but could not find associated sinf box.")); } @@ -334,7 +334,7 @@ Result SampleIterator::GetEncryptionScheme() { if (sampleInfo && !sampleInfo->mIsEncrypted) { // May not have sample encryption info, but if we do, it should match other // metadata. - return mozilla::Err(NS_LITERAL_CSTRING( + return mozilla::Err(nsLiteralCString( "Could not determine encryption scheme. Sample description entry " "indicates encryption, but sample encryption entry indicates sample is " "not encrypted. These should be consistent.")); @@ -345,7 +345,7 @@ Result SampleIterator::GetEncryptionScheme() { } else if (moofParser->mSinf.mDefaultEncryptionType == AtomType("cbcs")) { return CryptoScheme::Cbcs; } - return mozilla::Err(NS_LITERAL_CSTRING( + return mozilla::Err(nsLiteralCString( "Could not determine encryption scheme. Sample description entry " "reports sample is encrypted, but no scheme, or an unsupported scheme " "is in use.")); diff --git a/dom/media/mp4/MP4Decoder.cpp b/dom/media/mp4/MP4Decoder.cpp index 2dd7d926c902..a1ecebf29c2b 100644 --- a/dom/media/mp4/MP4Decoder.cpp +++ b/dom/media/mp4/MP4Decoder.cpp @@ -82,26 +82,25 @@ nsTArray> MP4Decoder::GetTracksInfo( if (IsAACCodecString(codec)) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/mp4a-latm"), aType)); + "audio/mp4a-latm"_ns, aType)); continue; } if (codec.EqualsLiteral("mp3")) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/mpeg"), aType)); + "audio/mpeg"_ns, aType)); continue; } if (codec.EqualsLiteral("opus") || codec.EqualsLiteral("flac")) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/") + NS_ConvertUTF16toUTF8(codec), - aType)); + "audio/"_ns + NS_ConvertUTF16toUTF8(codec), aType)); continue; } if (IsVP9CodecString(codec)) { auto trackInfo = CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/vp9"), aType); + "video/vp9"_ns, aType); uint8_t profile = 0; uint8_t level = 0; uint8_t bitDepth = 0; @@ -116,14 +115,14 @@ nsTArray> MP4Decoder::GetTracksInfo( if (IsAV1CodecString(codec)) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/av1"), aType)); + "video/av1"_ns, aType)); continue; } #endif if (isVideo && IsWhitelistedH264Codec(codec)) { auto trackInfo = CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/avc"), aType); + "video/avc"_ns, aType); uint8_t profile = 0, constraint = 0, level = 0; MOZ_ALWAYS_TRUE( ExtractH264CodecDetails(codec, profile, constraint, level)); @@ -161,11 +160,11 @@ bool MP4Decoder::IsSupportedType(const MediaContainerType& aType, aType.Type() == MEDIAMIMETYPE("audio/x-m4a")) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/mp4a-latm"), aType)); + "audio/mp4a-latm"_ns, aType)); } else { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/avc"), aType)); + "video/avc"_ns, aType)); } } diff --git a/dom/media/mp4/MP4Demuxer.cpp b/dom/media/mp4/MP4Demuxer.cpp index e2f0aa8ff292..c0d14a6663be 100644 --- a/dom/media/mp4/MP4Demuxer.cpp +++ b/dom/media/mp4/MP4Demuxer.cpp @@ -298,7 +298,7 @@ UniquePtr MP4Demuxer::GetCrypto() { UniquePtr crypto; if (!mCryptoInitData.IsEmpty()) { crypto.reset(new EncryptionInfo{}); - crypto->AddInitData(NS_LITERAL_STRING("cenc"), mCryptoInitData); + crypto->AddInitData(u"cenc"_ns, mCryptoInitData); } return crypto; } diff --git a/dom/media/ogg/OggCodecState.cpp b/dom/media/ogg/OggCodecState.cpp index ab1287c30b46..586c6a734ae4 100644 --- a/dom/media/ogg/OggCodecState.cpp +++ b/dom/media/ogg/OggCodecState.cpp @@ -398,7 +398,7 @@ bool TheoraState::Init() { } // Video track's frame sizes will not overflow. Activate the video track. - mInfo.mMimeType = NS_LITERAL_CSTRING("video/theora"); + mInfo.mMimeType = "video/theora"_ns; mInfo.mDisplay = display; mInfo.mImage = frame; mInfo.SetImageRect(picture); @@ -752,7 +752,7 @@ bool VorbisState::Init() { return mActive = false; } mHeaders.Erase(); - mInfo.mMimeType = NS_LITERAL_CSTRING("audio/vorbis"); + mInfo.mMimeType = "audio/vorbis"_ns; mInfo.mRate = mVorbisInfo.rate; mInfo.mChannels = mVorbisInfo.channels; mInfo.mBitDepth = 16; @@ -1012,7 +1012,7 @@ bool OpusState::Init(void) { mParser->mRate, mParser->mChannels, mParser->mStreams, mParser->mCoupledStreams, mParser->mMappingTable, &error); - mInfo.mMimeType = NS_LITERAL_CSTRING("audio/opus"); + mInfo.mMimeType = "audio/opus"_ns; mInfo.mRate = mParser->mRate; mInfo.mChannels = mParser->mChannels; mInfo.mBitDepth = 16; diff --git a/dom/media/ogg/OggDecoder.cpp b/dom/media/ogg/OggDecoder.cpp index 648d09bbd8d3..5f6d61f694c2 100644 --- a/dom/media/ogg/OggDecoder.cpp +++ b/dom/media/ogg/OggDecoder.cpp @@ -68,14 +68,12 @@ nsTArray> OggDecoder::GetTracksInfo( codec.EqualsLiteral("flac")) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/") + NS_ConvertUTF16toUTF8(codec), - aType)); + "audio/"_ns + NS_ConvertUTF16toUTF8(codec), aType)); } else { MOZ_ASSERT(codec.EqualsLiteral("theora")); tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/") + NS_ConvertUTF16toUTF8(codec), - aType)); + "video/"_ns + NS_ConvertUTF16toUTF8(codec), aType)); } } return tracks; diff --git a/dom/media/ogg/OggDemuxer.cpp b/dom/media/ogg/OggDemuxer.cpp index 98779d1d3ddb..a6bc68dac041 100644 --- a/dom/media/ogg/OggDemuxer.cpp +++ b/dom/media/ogg/OggDemuxer.cpp @@ -111,24 +111,24 @@ void OggDemuxer::SandboxDestroy::operator()(rlbox_sandbox_ogg* sandbox) { // (http://wiki.xiph.org/SkeletonHeaders) const nsString OggDemuxer::GetKind(const nsCString& aRole) { if (aRole.Find("audio/main") != -1 || aRole.Find("video/main") != -1) { - return NS_LITERAL_STRING("main"); + return u"main"_ns; } else if (aRole.Find("audio/alternate") != -1 || aRole.Find("video/alternate") != -1) { - return NS_LITERAL_STRING("alternative"); + return u"alternative"_ns; } else if (aRole.Find("audio/audiodesc") != -1) { - return NS_LITERAL_STRING("descriptions"); + return u"descriptions"_ns; } else if (aRole.Find("audio/described") != -1) { - return NS_LITERAL_STRING("main-desc"); + return u"main-desc"_ns; } else if (aRole.Find("audio/dub") != -1) { - return NS_LITERAL_STRING("translation"); + return u"translation"_ns; } else if (aRole.Find("audio/commentary") != -1) { - return NS_LITERAL_STRING("commentary"); + return u"commentary"_ns; } else if (aRole.Find("video/sign") != -1) { - return NS_LITERAL_STRING("sign"); + return u"sign"_ns; } else if (aRole.Find("video/captioned") != -1) { - return NS_LITERAL_STRING("captions"); + return u"captions"_ns; } else if (aRole.Find("video/subtitled") != -1) { - return NS_LITERAL_STRING("subtitles"); + return u"subtitles"_ns; } return EmptyString(); } diff --git a/dom/media/platforms/agnostic/AOMDecoder.h b/dom/media/platforms/agnostic/AOMDecoder.h index cdc43378a92e..da7b22ab2355 100644 --- a/dom/media/platforms/agnostic/AOMDecoder.h +++ b/dom/media/platforms/agnostic/AOMDecoder.h @@ -27,7 +27,7 @@ class AOMDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("av1 libaom video decoder"); + return "av1 libaom video decoder"_ns; } // Return true if aMimeType is a one of the strings used diff --git a/dom/media/platforms/agnostic/BlankDecoderModule.cpp b/dom/media/platforms/agnostic/BlankDecoderModule.cpp index 081fedf292e1..de5019fde2f9 100644 --- a/dom/media/platforms/agnostic/BlankDecoderModule.cpp +++ b/dom/media/platforms/agnostic/BlankDecoderModule.cpp @@ -115,8 +115,7 @@ already_AddRefed BlankDecoderModule::CreateVideoDecoder( UniquePtr creator = MakeUnique( config.mDisplay.width, config.mDisplay.height, aParams.mImageContainer); RefPtr decoder = new DummyMediaDataDecoder( - std::move(creator), NS_LITERAL_CSTRING("blank media data decoder"), - aParams); + std::move(creator), "blank media data decoder"_ns, aParams); return decoder.forget(); } @@ -126,8 +125,7 @@ already_AddRefed BlankDecoderModule::CreateAudioDecoder( UniquePtr creator = MakeUnique(config.mChannels, config.mRate); RefPtr decoder = new DummyMediaDataDecoder( - std::move(creator), NS_LITERAL_CSTRING("blank media data decoder"), - aParams); + std::move(creator), "blank media data decoder"_ns, aParams); return decoder.forget(); } diff --git a/dom/media/platforms/agnostic/DAV1DDecoder.h b/dom/media/platforms/agnostic/DAV1DDecoder.h index 297d1fa1dd63..c136ca6e171a 100644 --- a/dom/media/platforms/agnostic/DAV1DDecoder.h +++ b/dom/media/platforms/agnostic/DAV1DDecoder.h @@ -27,7 +27,7 @@ class DAV1DDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("av1 libdav1d video decoder"); + return "av1 libdav1d video decoder"_ns; } void ReleaseDataBuffer(const uint8_t* buf); diff --git a/dom/media/platforms/agnostic/DummyMediaDataDecoder.cpp b/dom/media/platforms/agnostic/DummyMediaDataDecoder.cpp index f73c5b3bc3ef..6cf064514cc3 100644 --- a/dom/media/platforms/agnostic/DummyMediaDataDecoder.cpp +++ b/dom/media/platforms/agnostic/DummyMediaDataDecoder.cpp @@ -66,7 +66,7 @@ RefPtr DummyMediaDataDecoder::Flush() { } nsCString DummyMediaDataDecoder::GetDescriptionName() const { - return NS_LITERAL_CSTRING("blank media data decoder"); + return "blank media data decoder"_ns; } MediaDataDecoder::ConversionRequired DummyMediaDataDecoder::NeedsConversion() diff --git a/dom/media/platforms/agnostic/NullDecoderModule.cpp b/dom/media/platforms/agnostic/NullDecoderModule.cpp index dbc016fcc011..17db1d526daa 100644 --- a/dom/media/platforms/agnostic/NullDecoderModule.cpp +++ b/dom/media/platforms/agnostic/NullDecoderModule.cpp @@ -29,8 +29,7 @@ class NullDecoderModule : public PlatformDecoderModule { const CreateDecoderParams& aParams) override { UniquePtr creator = MakeUnique(); RefPtr decoder = new DummyMediaDataDecoder( - std::move(creator), NS_LITERAL_CSTRING("null media data decoder"), - aParams); + std::move(creator), "null media data decoder"_ns, aParams); return decoder.forget(); } diff --git a/dom/media/platforms/agnostic/OpusDecoder.h b/dom/media/platforms/agnostic/OpusDecoder.h index 9b324248b4a4..21a4c2bcbbaa 100644 --- a/dom/media/platforms/agnostic/OpusDecoder.h +++ b/dom/media/platforms/agnostic/OpusDecoder.h @@ -31,7 +31,7 @@ class OpusDataDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("opus audio decoder"); + return "opus audio decoder"_ns; } // Return true if mimetype is Opus diff --git a/dom/media/platforms/agnostic/TheoraDecoder.h b/dom/media/platforms/agnostic/TheoraDecoder.h index 55126e1e7ee2..1efe9535d929 100644 --- a/dom/media/platforms/agnostic/TheoraDecoder.h +++ b/dom/media/platforms/agnostic/TheoraDecoder.h @@ -30,7 +30,7 @@ class TheoraDecoder : public MediaDataDecoder, static bool IsTheora(const nsACString& aMimeType); nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("theora video decoder"); + return "theora video decoder"_ns; } private: diff --git a/dom/media/platforms/agnostic/VPXDecoder.h b/dom/media/platforms/agnostic/VPXDecoder.h index 6a5602d66d36..fc35342e0273 100644 --- a/dom/media/platforms/agnostic/VPXDecoder.h +++ b/dom/media/platforms/agnostic/VPXDecoder.h @@ -30,7 +30,7 @@ class VPXDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("libvpx video decoder"); + return "libvpx video decoder"_ns; } enum Codec : uint8_t { diff --git a/dom/media/platforms/agnostic/VorbisDecoder.h b/dom/media/platforms/agnostic/VorbisDecoder.h index ad1fad216e40..c657a83c2426 100644 --- a/dom/media/platforms/agnostic/VorbisDecoder.h +++ b/dom/media/platforms/agnostic/VorbisDecoder.h @@ -32,7 +32,7 @@ class VorbisDataDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("vorbis audio decoder"); + return "vorbis audio decoder"_ns; } // Return true if mimetype is Vorbis diff --git a/dom/media/platforms/agnostic/WAVDecoder.h b/dom/media/platforms/agnostic/WAVDecoder.h index 220631f7bae8..47e1ab5e3da5 100644 --- a/dom/media/platforms/agnostic/WAVDecoder.h +++ b/dom/media/platforms/agnostic/WAVDecoder.h @@ -27,7 +27,7 @@ class WaveDataDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("wave audio decoder"); + return "wave audio decoder"_ns; } private: diff --git a/dom/media/platforms/agnostic/eme/ChromiumCDMVideoDecoder.cpp b/dom/media/platforms/agnostic/eme/ChromiumCDMVideoDecoder.cpp index e92cb7dedb75..23f15f997585 100644 --- a/dom/media/platforms/agnostic/eme/ChromiumCDMVideoDecoder.cpp +++ b/dom/media/platforms/agnostic/eme/ChromiumCDMVideoDecoder.cpp @@ -82,7 +82,7 @@ RefPtr ChromiumCDMVideoDecoder::Init() { } nsCString ChromiumCDMVideoDecoder::GetDescriptionName() const { - return NS_LITERAL_CSTRING("chromium cdm video decoder"); + return "chromium cdm video decoder"_ns; } MediaDataDecoder::ConversionRequired ChromiumCDMVideoDecoder::NeedsConversion() diff --git a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp index f4c6e5719737..91c6d964aca3 100644 --- a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp +++ b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.cpp @@ -67,18 +67,18 @@ bool GMPDecoderModule::SupportsMimeType(const nsACString& aMimeType, return false; } - nsCString api = NS_LITERAL_CSTRING(CHROMIUM_CDM_API); + nsCString api = nsLiteralCString(CHROMIUM_CDM_API); if (MP4Decoder::IsH264(aMimeType)) { - return HaveGMPFor(api, {NS_LITERAL_CSTRING("h264"), aGMP.value()}); + return HaveGMPFor(api, {"h264"_ns, aGMP.value()}); } if (VPXDecoder::IsVP9(aMimeType)) { - return HaveGMPFor(api, {NS_LITERAL_CSTRING("vp9"), aGMP.value()}); + return HaveGMPFor(api, {"vp9"_ns, aGMP.value()}); } if (VPXDecoder::IsVP8(aMimeType)) { - return HaveGMPFor(api, {NS_LITERAL_CSTRING("vp8"), aGMP.value()}); + return HaveGMPFor(api, {"vp8"_ns, aGMP.value()}); } return false; diff --git a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h index 83457c3e8dcb..040f998b1c7a 100644 --- a/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h +++ b/dom/media/platforms/agnostic/gmp/GMPDecoderModule.h @@ -21,7 +21,7 @@ // (because NodeIds are random strings which can't contain the '-' character), // so there's no way a malicious GMP can harvest, store, and then report any // privacy sensitive data about what users are watching. -# define SHARED_GMP_DECODING_NODE_ID NS_LITERAL_CSTRING("gmp-shared-decoding") +# define SHARED_GMP_DECODING_NODE_ID "gmp-shared-decoding"_ns namespace mozilla { diff --git a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp index 2cce9799e28c..36a4e576f84f 100644 --- a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp +++ b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.cpp @@ -127,11 +127,11 @@ GMPVideoDecoder::GMPVideoDecoder(const GMPVideoDecoderParams& aParams) void GMPVideoDecoder::InitTags(nsTArray& aTags) { if (MP4Decoder::IsH264(mConfig.mMimeType)) { - aTags.AppendElement(NS_LITERAL_CSTRING("h264")); + aTags.AppendElement("h264"_ns); } else if (VPXDecoder::IsVP8(mConfig.mMimeType)) { - aTags.AppendElement(NS_LITERAL_CSTRING("vp8")); + aTags.AppendElement("vp8"_ns); } else if (VPXDecoder::IsVP9(mConfig.mMimeType)) { - aTags.AppendElement(NS_LITERAL_CSTRING("vp9")); + aTags.AppendElement("vp9"_ns); } } diff --git a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h index 3619eed456d0..407a040d226a 100644 --- a/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h +++ b/dom/media/platforms/agnostic/gmp/GMPVideoDecoder.h @@ -40,7 +40,7 @@ class GMPVideoDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("gmp video decoder"); + return "gmp video decoder"_ns; } ConversionRequired NeedsConversion() const override { return mConvertToAnnexB ? ConversionRequired::kNeedAnnexB diff --git a/dom/media/platforms/android/AndroidDataEncoder.h b/dom/media/platforms/android/AndroidDataEncoder.h index cacd779cdce0..6b5f5bf04061 100644 --- a/dom/media/platforms/android/AndroidDataEncoder.h +++ b/dom/media/platforms/android/AndroidDataEncoder.h @@ -28,9 +28,7 @@ class AndroidDataEncoder final : public MediaDataEncoder { RefPtr Shutdown() override; RefPtr SetBitrate(const Rate aBitsPerSec) override; - nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("Android Encoder"); - } + nsCString GetDescriptionName() const override { return "Android Encoder"_ns; } private: class CallbacksSupport final : public JavaCallbacksSupport { diff --git a/dom/media/platforms/android/RemoteDataDecoder.cpp b/dom/media/platforms/android/RemoteDataDecoder.cpp index 7c08080e263d..ee24e4391886 100644 --- a/dom/media/platforms/android/RemoteDataDecoder.cpp +++ b/dom/media/platforms/android/RemoteDataDecoder.cpp @@ -342,15 +342,13 @@ class RemoteAudioDecoder : public RemoteDataDecoder { JNIEnv* const env = jni::GetEnvForThread(); bool formatHasCSD = false; - NS_ENSURE_SUCCESS_VOID( - aFormat->ContainsKey(NS_LITERAL_STRING("csd-0"), &formatHasCSD)); + NS_ENSURE_SUCCESS_VOID(aFormat->ContainsKey(u"csd-0"_ns, &formatHasCSD)); if (!formatHasCSD && aConfig.mCodecSpecificConfig->Length() >= 2) { jni::ByteBuffer::LocalRef buffer(env); buffer = jni::ByteBuffer::New(aConfig.mCodecSpecificConfig->Elements(), aConfig.mCodecSpecificConfig->Length()); - NS_ENSURE_SUCCESS_VOID( - aFormat->SetByteBuffer(NS_LITERAL_STRING("csd-0"), buffer)); + NS_ENSURE_SUCCESS_VOID(aFormat->SetByteBuffer(u"csd-0"_ns, buffer)); } } @@ -422,7 +420,7 @@ class RemoteAudioDecoder : public RemoteDataDecoder { void HandleOutputFormatChanged( java::sdk::MediaFormat::Param aFormat) override { int32_t outputChannels = 0; - aFormat->GetInteger(NS_LITERAL_STRING("channel-count"), &outputChannels); + aFormat->GetInteger(u"channel-count"_ns, &outputChannels); AudioConfig::ChannelLayout layout(outputChannels); if (!layout.IsValid()) { mDecoder->Error(MediaResult( @@ -432,7 +430,7 @@ class RemoteAudioDecoder : public RemoteDataDecoder { } int32_t sampleRate = 0; - aFormat->GetInteger(NS_LITERAL_STRING("sample-rate"), &sampleRate); + aFormat->GetInteger(u"sample-rate"_ns, &sampleRate); LOG("Audio output format changed: channels:%d sample rate:%d", outputChannels, sampleRate); diff --git a/dom/media/platforms/android/RemoteDataDecoder.h b/dom/media/platforms/android/RemoteDataDecoder.h index 81bed4c552e0..740f387552d4 100644 --- a/dom/media/platforms/android/RemoteDataDecoder.h +++ b/dom/media/platforms/android/RemoteDataDecoder.h @@ -32,7 +32,7 @@ class RemoteDataDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("android decoder (remote)"); + return "android decoder (remote)"_ns; } protected: diff --git a/dom/media/platforms/apple/AppleATDecoder.h b/dom/media/platforms/apple/AppleATDecoder.h index d1bd4a676033..c66618e5acc5 100644 --- a/dom/media/platforms/apple/AppleATDecoder.h +++ b/dom/media/platforms/apple/AppleATDecoder.h @@ -31,7 +31,7 @@ class AppleATDecoder : public MediaDataDecoder, RefPtr Shutdown() override; nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("apple coremedia decoder"); + return "apple coremedia decoder"_ns; } // Callbacks also need access to the config. diff --git a/dom/media/platforms/apple/AppleVTDecoder.h b/dom/media/platforms/apple/AppleVTDecoder.h index e1caf864570e..3533634d6ab0 100644 --- a/dom/media/platforms/apple/AppleVTDecoder.h +++ b/dom/media/platforms/apple/AppleVTDecoder.h @@ -55,9 +55,8 @@ class AppleVTDecoder : public MediaDataDecoder, } nsCString GetDescriptionName() const override { - return mIsHardwareAccelerated - ? NS_LITERAL_CSTRING("apple hardware VT decoder") - : NS_LITERAL_CSTRING("apple software VT decoder"); + return mIsHardwareAccelerated ? "apple hardware VT decoder"_ns + : "apple software VT decoder"_ns; } ConversionRequired NeedsConversion() const override { diff --git a/dom/media/platforms/apple/AppleVTEncoder.h b/dom/media/platforms/apple/AppleVTEncoder.h index 000f3bb9adcb..d11c3a4c1fe6 100644 --- a/dom/media/platforms/apple/AppleVTEncoder.h +++ b/dom/media/platforms/apple/AppleVTEncoder.h @@ -40,9 +40,8 @@ class AppleVTEncoder final : public MediaDataEncoder { nsCString GetDescriptionName() const override { MOZ_ASSERT(mSession); - return mIsHardwareAccelerated - ? NS_LITERAL_CSTRING("apple hardware VT encoder") - : NS_LITERAL_CSTRING("apple software VT encoder"); + return mIsHardwareAccelerated ? "apple hardware VT encoder"_ns + : "apple software VT encoder"_ns; } void OutputFrame(CMSampleBufferRef aBuffer); diff --git a/dom/media/platforms/ffmpeg/FFmpegAudioDecoder.h b/dom/media/platforms/ffmpeg/FFmpegAudioDecoder.h index 2cfdf15a1356..6187aaca8bf2 100644 --- a/dom/media/platforms/ffmpeg/FFmpegAudioDecoder.h +++ b/dom/media/platforms/ffmpeg/FFmpegAudioDecoder.h @@ -33,7 +33,7 @@ class FFmpegAudioDecoder void InitCodecContext() override; static AVCodecID GetCodecId(const nsACString& aMimeType); nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("ffmpeg audio decoder"); + return "ffmpeg audio decoder"_ns; } private: diff --git a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.h b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.h index 7a458adf9d95..5b7bd2b524ca 100644 --- a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.h +++ b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.h @@ -110,9 +110,9 @@ class FFmpegVideoDecoder void InitCodecContext() override; nsCString GetDescriptionName() const override { #ifdef USING_MOZFFVPX - return NS_LITERAL_CSTRING("ffvpx video decoder"); + return "ffvpx video decoder"_ns; #else - return NS_LITERAL_CSTRING("ffmpeg video decoder"); + return "ffmpeg video decoder"_ns; #endif } ConversionRequired NeedsConversion() const override { diff --git a/dom/media/platforms/omx/OmxDataDecoder.h b/dom/media/platforms/omx/OmxDataDecoder.h index 6e2c65213219..cc7d3af1ef37 100644 --- a/dom/media/platforms/omx/OmxDataDecoder.h +++ b/dom/media/platforms/omx/OmxDataDecoder.h @@ -73,9 +73,7 @@ class OmxDataDecoder : public MediaDataDecoder, RefPtr Flush() override; RefPtr Shutdown() override; - nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("omx decoder"); - } + nsCString GetDescriptionName() const override { return "omx decoder"_ns; } ConversionRequired NeedsConversion() const override { return ConversionRequired::kNeedAnnexB; diff --git a/dom/media/platforms/wmf/WMFAudioMFTManager.h b/dom/media/platforms/wmf/WMFAudioMFTManager.h index d39ee2866ed4..4271d5ef8dc2 100644 --- a/dom/media/platforms/wmf/WMFAudioMFTManager.h +++ b/dom/media/platforms/wmf/WMFAudioMFTManager.h @@ -33,7 +33,7 @@ class WMFAudioMFTManager : public MFTManager { TrackInfo::TrackType GetType() override { return TrackInfo::kAudioTrack; } nsCString GetDescriptionName() const override { - return NS_LITERAL_CSTRING("wmf audio decoder"); + return "wmf audio decoder"_ns; } private: diff --git a/dom/media/platforms/wmf/WMFMediaDataDecoder.h b/dom/media/platforms/wmf/WMFMediaDataDecoder.h index 40df802e0f56..a62723c947e3 100644 --- a/dom/media/platforms/wmf/WMFMediaDataDecoder.h +++ b/dom/media/platforms/wmf/WMFMediaDataDecoder.h @@ -102,8 +102,7 @@ class WMFMediaDataDecoder bool IsHardwareAccelerated(nsACString& aFailureReason) const override; nsCString GetDescriptionName() const override { - return mMFTManager ? mMFTManager->GetDescriptionName() - : NS_LITERAL_CSTRING(""); + return mMFTManager ? mMFTManager->GetDescriptionName() : ""_ns; } ConversionRequired NeedsConversion() const override { diff --git a/dom/media/platforms/wmf/WMFUtils.cpp b/dom/media/platforms/wmf/WMFUtils.cpp index 99f583f4d024..b56ff47c90de 100644 --- a/dom/media/platforms/wmf/WMFUtils.cpp +++ b/dom/media/platforms/wmf/WMFUtils.cpp @@ -161,7 +161,7 @@ nsString GetProgramW6432Path() { } if (!programPath) { - return NS_LITERAL_STRING("C:\\Program Files"); + return u"C:\\Program Files"_ns; } return NS_ConvertUTF8toUTF16(programPath); } diff --git a/dom/media/platforms/wrappers/MediaChangeMonitor.h b/dom/media/platforms/wrappers/MediaChangeMonitor.h index dd80291c1775..868c2a27b912 100644 --- a/dom/media/platforms/wrappers/MediaChangeMonitor.h +++ b/dom/media/platforms/wrappers/MediaChangeMonitor.h @@ -43,7 +43,7 @@ class MediaChangeMonitor : public MediaDataDecoder, if (mDecoder) { return mDecoder->GetDescriptionName(); } - return NS_LITERAL_CSTRING("MediaChangeMonitor decoder (pending)"); + return "MediaChangeMonitor decoder (pending)"_ns; } void SetSeekThreshold(const media::TimeUnit& aTime) override; bool SupportDecoderRecycling() const override { diff --git a/dom/media/systemservices/CamerasParent.cpp b/dom/media/systemservices/CamerasParent.cpp index c84b7e42d068..2f5de8881feb 100644 --- a/dom/media/systemservices/CamerasParent.cpp +++ b/dom/media/systemservices/CamerasParent.cpp @@ -675,8 +675,7 @@ static bool HasCameraPermission(const uint64_t& aWindowId) { nsresult rv; // Name used with nsIPermissionManager - static const nsLiteralCString cameraPermission = - NS_LITERAL_CSTRING("MediaManagerVideo"); + static const nsLiteralCString cameraPermission = "MediaManagerVideo"_ns; nsCOMPtr mgr = do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -1056,7 +1055,7 @@ void CamerasParent::ActorDestroy(ActorDestroyReason aWhy) { nsString CamerasParent::GetNewName() { static volatile uint64_t counter = 0; - nsString name(NS_LITERAL_STRING("CamerasParent ")); + nsString name(u"CamerasParent "_ns); name.AppendInt(++counter); return name; } @@ -1088,7 +1087,7 @@ CamerasParent::CamerasParent() RefPtr self(this); NS_DispatchToMainThread(NewRunnableFrom([self]() { nsresult rv = GetShutdownBarrier()->AddBlocker( - self, NS_LITERAL_STRING(__FILE__), __LINE__, NS_LITERAL_STRING("")); + self, NS_LITERAL_STRING(__FILE__), __LINE__, u""_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); // Start the thread diff --git a/dom/media/systemservices/MediaParent.cpp b/dom/media/systemservices/MediaParent.cpp index f5031e9d166d..42304a93cec3 100644 --- a/dom/media/systemservices/MediaParent.cpp +++ b/dom/media/systemservices/MediaParent.cpp @@ -457,7 +457,7 @@ mozilla::ipc::IPCResult Parent::RecvGetPrincipalKey( GetCurrentSerialEventTarget(), __func__, [aResolve](const PrincipalKeyPromise::ResolveOrRejectValue& aValue) { if (aValue.IsReject()) { - aResolve(NS_LITERAL_CSTRING("")); + aResolve(""_ns); } else { aResolve(aValue.ResolveValue()); } diff --git a/dom/media/wave/WaveDecoder.cpp b/dom/media/wave/WaveDecoder.cpp index 53404f18bd50..2aea6b417820 100644 --- a/dom/media/wave/WaveDecoder.cpp +++ b/dom/media/wave/WaveDecoder.cpp @@ -41,16 +41,14 @@ nsTArray> WaveDecoder::GetTracksInfo( if (codecs.IsEmpty()) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/x-wav"), aType)); + "audio/x-wav"_ns, aType)); return tracks; } for (const auto& codec : codecs.Range()) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/wave; codecs=") + - NS_ConvertUTF16toUTF8(codec), - aType)); + "audio/wave; codecs="_ns + NS_ConvertUTF16toUTF8(codec), aType)); } return tracks; } diff --git a/dom/media/wave/WaveDemuxer.cpp b/dom/media/wave/WaveDemuxer.cpp index c8b57a226337..41c2bca26f5c 100644 --- a/dom/media/wave/WaveDemuxer.cpp +++ b/dom/media/wave/WaveDemuxer.cpp @@ -237,20 +237,16 @@ bool WAVTrackDemuxer::ListChunkParserInit(uint32_t aChunkSize) { switch (id) { case 0x49415254: // IART - mInfo->mTags.AppendElement( - MetadataTag(NS_LITERAL_CSTRING("artist"), val)); + mInfo->mTags.AppendElement(MetadataTag("artist"_ns, val)); break; case 0x49434d54: // ICMT - mInfo->mTags.AppendElement( - MetadataTag(NS_LITERAL_CSTRING("comments"), val)); + mInfo->mTags.AppendElement(MetadataTag("comments"_ns, val)); break; case 0x49474e52: // IGNR - mInfo->mTags.AppendElement( - MetadataTag(NS_LITERAL_CSTRING("genre"), val)); + mInfo->mTags.AppendElement(MetadataTag("genre"_ns, val)); break; case 0x494e414d: // INAM - mInfo->mTags.AppendElement( - MetadataTag(NS_LITERAL_CSTRING("name"), val)); + mInfo->mTags.AppendElement(MetadataTag("name"_ns, val)); break; } diff --git a/dom/media/webaudio/AudioBufferSourceNode.cpp b/dom/media/webaudio/AudioBufferSourceNode.cpp index 355de5398069..581735181d97 100644 --- a/dom/media/webaudio/AudioBufferSourceNode.cpp +++ b/dom/media/webaudio/AudioBufferSourceNode.cpp @@ -796,7 +796,7 @@ void AudioBufferSourceNode::NotifyMainThreadTrackEnded() { return NS_OK; } - mNode->DispatchTrustedEvent(NS_LITERAL_STRING("ended")); + mNode->DispatchTrustedEvent(u"ended"_ns); // Release track resources. mNode->DestroyMediaTrack(); return NS_OK; diff --git a/dom/media/webaudio/AudioContext.cpp b/dom/media/webaudio/AudioContext.cpp index 5fdcbacd8e8d..7fd8690b3f5c 100644 --- a/dom/media/webaudio/AudioContext.cpp +++ b/dom/media/webaudio/AudioContext.cpp @@ -811,7 +811,7 @@ class OnStateChangeTask final : public Runnable { return nsContentUtils::DispatchTrustedEvent( doc, static_cast(mAudioContext), - NS_LITERAL_STRING("statechange"), CanBubble::eNo, Cancelable::eNo); + u"statechange"_ns, CanBubble::eNo, Cancelable::eNo); } private: @@ -1095,8 +1095,8 @@ void AudioContext::ReportBlocked() { AUTOPLAY_LOG("Dispatch `blocked` event for AudioContext %p", self.get()); nsContentUtils::DispatchTrustedEvent( - doc, static_cast(self), - NS_LITERAL_STRING("blocked"), CanBubble::eNo, Cancelable::eNo); + doc, static_cast(self), u"blocked"_ns, + CanBubble::eNo, Cancelable::eNo); }); Dispatch(r.forget()); } @@ -1277,7 +1277,7 @@ void AudioContext::ReportToConsole(uint32_t aErrorFlags, MOZ_ASSERT(aMsg); Document* doc = GetParentObject() ? GetParentObject()->GetExtantDoc() : nullptr; - nsContentUtils::ReportToConsole(aErrorFlags, NS_LITERAL_CSTRING("Media"), doc, + nsContentUtils::ReportToConsole(aErrorFlags, "Media"_ns, doc, nsContentUtils::eDOM_PROPERTIES, aMsg); } diff --git a/dom/media/webaudio/AudioDestinationNode.cpp b/dom/media/webaudio/AudioDestinationNode.cpp index 67f6c7dceda2..0542c0e6ab16 100644 --- a/dom/media/webaudio/AudioDestinationNode.cpp +++ b/dom/media/webaudio/AudioDestinationNode.cpp @@ -46,8 +46,8 @@ class OnCompleteTask final : public Runnable { param.mRenderedBuffer = mRenderedBuffer; RefPtr event = - OfflineAudioCompletionEvent::Constructor( - mAudioContext, NS_LITERAL_STRING("complete"), param); + OfflineAudioCompletionEvent::Constructor(mAudioContext, u"complete"_ns, + param); mAudioContext->DispatchTrustedEvent(event); return NS_OK; @@ -612,8 +612,7 @@ void AudioDestinationNode::CreateAudioWakeLockIfNeeded() { NS_ENSURE_TRUE_VOID(pmService); ErrorResult rv; - mWakeLock = pmService->NewWakeLock(NS_LITERAL_STRING("audio-playing"), - GetOwner(), rv); + mWakeLock = pmService->NewWakeLock(u"audio-playing"_ns, GetOwner(), rv); } } diff --git a/dom/media/webaudio/AudioProcessingEvent.h b/dom/media/webaudio/AudioProcessingEvent.h index 15077b0e8ce2..88dbbb841c84 100644 --- a/dom/media/webaudio/AudioProcessingEvent.h +++ b/dom/media/webaudio/AudioProcessingEvent.h @@ -28,8 +28,7 @@ class AudioProcessingEvent final : public Event { using Event::InitEvent; void InitEvent(AudioBuffer* aInputBuffer, uint32_t aNumberOfInputChannels, double aPlaybackTime) { - InitEvent(NS_LITERAL_STRING("audioprocess"), CanBubble::eNo, - Cancelable::eNo); + InitEvent(u"audioprocess"_ns, CanBubble::eNo, Cancelable::eNo); mInputBuffer = aInputBuffer; mNumberOfInputChannels = aNumberOfInputChannels; mPlaybackTime = aPlaybackTime; diff --git a/dom/media/webaudio/AudioWorkletGlobalScope.cpp b/dom/media/webaudio/AudioWorkletGlobalScope.cpp index 994864b7b207..c3c7ee85352d 100644 --- a/dom/media/webaudio/AudioWorkletGlobalScope.cpp +++ b/dom/media/webaudio/AudioWorkletGlobalScope.cpp @@ -244,10 +244,9 @@ AudioParamDescriptorMap AudioWorkletGlobalScope::DescriptorsFromJS( for (const auto& descriptor : res) { if (namesSet.Contains(descriptor.mName)) { - aRv.ThrowNotSupportedError( - NS_LITERAL_CSTRING("Duplicated name \"") + - NS_ConvertUTF16toUTF8(descriptor.mName) + - NS_LITERAL_CSTRING("\" in parameterDescriptors.")); + aRv.ThrowNotSupportedError("Duplicated name \""_ns + + NS_ConvertUTF16toUTF8(descriptor.mName) + + "\" in parameterDescriptors."_ns); return AudioParamDescriptorMap(); } @@ -258,19 +257,19 @@ AudioParamDescriptorMap AudioWorkletGlobalScope::DescriptorsFromJS( if (descriptor.mMinValue > descriptor.mMaxValue) { aRv.ThrowInvalidStateError( - NS_LITERAL_CSTRING("In parameterDescriptors, ") + + "In parameterDescriptors, "_ns + NS_ConvertUTF16toUTF8(descriptor.mName) + - NS_LITERAL_CSTRING(" minValue should be smaller than maxValue.")); + " minValue should be smaller than maxValue."_ns); return AudioParamDescriptorMap(); } if (descriptor.mDefaultValue < descriptor.mMinValue || descriptor.mDefaultValue > descriptor.mMaxValue) { aRv.ThrowInvalidStateError( - NS_LITERAL_CSTRING("In parameterDescriptors, ") + + "In parameterDescriptors, "_ns + NS_ConvertUTF16toUTF8(descriptor.mName) + - NS_LITERAL_CSTRING(" defaultValue is out of the range defined by " - "minValue and maxValue.")); + nsLiteralCString(" defaultValue is out of the range defined by " + "minValue and maxValue.")); return AudioParamDescriptorMap(); } } diff --git a/dom/media/webaudio/AudioWorkletNode.cpp b/dom/media/webaudio/AudioWorkletNode.cpp index 8f116064f3c9..0c7e1ce625dc 100644 --- a/dom/media/webaudio/AudioWorkletNode.cpp +++ b/dom/media/webaudio/AudioWorkletNode.cpp @@ -666,9 +666,8 @@ already_AddRefed AudioWorkletNode::Constructor( aAudioContext.GetParamMapForWorkletName(aName); if (!parameterDescriptors) { // Not using nsPrintfCString in case aName has embedded nulls. - aRv.ThrowInvalidStateError( - NS_LITERAL_CSTRING("Unknown AudioWorklet name '") + - NS_ConvertUTF16toUTF8(aName) + NS_LITERAL_CSTRING("'")); + aRv.ThrowInvalidStateError("Unknown AudioWorklet name '"_ns + + NS_ConvertUTF16toUTF8(aName) + "'"_ns); return nullptr; } @@ -855,8 +854,8 @@ void AudioWorkletNode::DispatchProcessorErrorEvent( init.mFilename = aDetails.mFilename; init.mLineno = aDetails.mLineno; init.mColno = aDetails.mColno; - RefPtr errorEvent = ErrorEvent::Constructor( - this, NS_LITERAL_STRING("processorerror"), init); + RefPtr errorEvent = + ErrorEvent::Constructor(this, u"processorerror"_ns, init); MOZ_ASSERT(errorEvent); DispatchTrustedEvent(errorEvent); } diff --git a/dom/media/webaudio/ConstantSourceNode.cpp b/dom/media/webaudio/ConstantSourceNode.cpp index 44ce49b0ad2d..dc57dff84090 100644 --- a/dom/media/webaudio/ConstantSourceNode.cpp +++ b/dom/media/webaudio/ConstantSourceNode.cpp @@ -257,7 +257,7 @@ void ConstantSourceNode::NotifyMainThreadTrackEnded() { return NS_OK; } - mNode->DispatchTrustedEvent(NS_LITERAL_STRING("ended")); + mNode->DispatchTrustedEvent(u"ended"_ns); // Release track resources. mNode->DestroyMediaTrack(); return NS_OK; diff --git a/dom/media/webaudio/MediaBufferDecoder.cpp b/dom/media/webaudio/MediaBufferDecoder.cpp index dfb6c301f5d0..50e4b482629e 100644 --- a/dom/media/webaudio/MediaBufferDecoder.cpp +++ b/dom/media/webaudio/MediaBufferDecoder.cpp @@ -721,9 +721,9 @@ void WebAudioDecodeJob::OnFailure(ErrorCode aErrorCode) { if (nsPIDOMWindowInner* pWindow = mContext->GetParentObject()) { doc = pWindow->GetExtantDoc(); } - nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Media"), doc, - nsContentUtils::eDOM_PROPERTIES, errorMessage); + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "Media"_ns, doc, + nsContentUtils::eDOM_PROPERTIES, + errorMessage); // Ignore errors in calling the callback, since there is not much that we can // do about it here. diff --git a/dom/media/webaudio/MediaStreamAudioSourceNode.cpp b/dom/media/webaudio/MediaStreamAudioSourceNode.cpp index ec9c97d6c8fa..1539523f84e5 100644 --- a/dom/media/webaudio/MediaStreamAudioSourceNode.cpp +++ b/dom/media/webaudio/MediaStreamAudioSourceNode.cpp @@ -100,9 +100,8 @@ void MediaStreamAudioSourceNode::AttachToTrack( if (NS_WARN_IF(Context()->Graph() != aTrack->Graph())) { nsCOMPtr pWindow = Context()->GetParentObject(); Document* document = pWindow ? pWindow->GetExtantDoc() : nullptr; - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Web Audio"), document, - nsContentUtils::eDOM_PROPERTIES, + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Web Audio"_ns, + document, nsContentUtils::eDOM_PROPERTIES, "MediaStreamAudioSourceNodeDifferentRate"); // This is not a spec-required exception, just a limitation of our // implementation. @@ -242,9 +241,9 @@ void MediaStreamAudioSourceNode::PrincipalChanged( track->SetInt32Parameter(MediaStreamAudioSourceNodeEngine::ENABLE, enabled); if (!enabled && doc) { - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Web Audio"), doc, - nsContentUtils::eDOM_PROPERTIES, CrossOriginErrorString()); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Web Audio"_ns, + doc, nsContentUtils::eDOM_PROPERTIES, + CrossOriginErrorString()); } } diff --git a/dom/media/webaudio/MediaStreamTrackAudioSourceNode.cpp b/dom/media/webaudio/MediaStreamTrackAudioSourceNode.cpp index 2904d3f10c50..430a74a922f8 100644 --- a/dom/media/webaudio/MediaStreamTrackAudioSourceNode.cpp +++ b/dom/media/webaudio/MediaStreamTrackAudioSourceNode.cpp @@ -53,9 +53,8 @@ MediaStreamTrackAudioSourceNode::Create( aAudioContext.Graph() != aOptions.mMediaStreamTrack->Graph()) { nsCOMPtr pWindow = aAudioContext.GetParentObject(); Document* document = pWindow ? pWindow->GetExtantDoc() : nullptr; - nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Web Audio"), document, - nsContentUtils::eDOM_PROPERTIES, + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Web Audio"_ns, + document, nsContentUtils::eDOM_PROPERTIES, "MediaStreamAudioSourceNodeDifferentRate"); // This is not a spec-required exception, just a limitation of our // implementation. @@ -166,9 +165,9 @@ void MediaStreamTrackAudioSourceNode::PrincipalChanged( fprintf(stderr, "NOW: %s", enabled ? "enabled" : "disabled"); if (!enabled && doc) { - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Web Audio"), doc, - nsContentUtils::eDOM_PROPERTIES, CrossOriginErrorString()); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Web Audio"_ns, + doc, nsContentUtils::eDOM_PROPERTIES, + CrossOriginErrorString()); } } diff --git a/dom/media/webaudio/OscillatorNode.cpp b/dom/media/webaudio/OscillatorNode.cpp index 2089ce170c09..ed51095531f6 100644 --- a/dom/media/webaudio/OscillatorNode.cpp +++ b/dom/media/webaudio/OscillatorNode.cpp @@ -521,7 +521,7 @@ void OscillatorNode::NotifyMainThreadTrackEnded() { return NS_OK; } - mNode->DispatchTrustedEvent(NS_LITERAL_STRING("ended")); + mNode->DispatchTrustedEvent(u"ended"_ns); // Release track resources. mNode->DestroyMediaTrack(); return NS_OK; diff --git a/dom/media/webm/WebMDecoder.cpp b/dom/media/webm/WebMDecoder.cpp index 1887f8567707..515b380d58ca 100644 --- a/dom/media/webm/WebMDecoder.cpp +++ b/dom/media/webm/WebMDecoder.cpp @@ -43,18 +43,17 @@ nsTArray> WebMDecoder::GetTracksInfo( if (codec.EqualsLiteral("opus") || codec.EqualsLiteral("vorbis")) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("audio/") + NS_ConvertUTF16toUTF8(codec), - aType)); + "audio/"_ns + NS_ConvertUTF16toUTF8(codec), aType)); continue; } if (isVideo) { UniquePtr trackInfo; if (IsVP9CodecString(codec)) { trackInfo = CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/vp9"), aType); + "video/vp9"_ns, aType); } else if (IsVP8CodecString(codec)) { trackInfo = CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/vp8"), aType); + "video/vp8"_ns, aType); } if (trackInfo) { uint8_t profile = 0; @@ -72,7 +71,7 @@ nsTArray> WebMDecoder::GetTracksInfo( if (StaticPrefs::media_av1_enabled() && IsAV1CodecString(codec)) { tracks.AppendElement( CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters( - NS_LITERAL_CSTRING("video/av1"), aType)); + "video/av1"_ns, aType)); continue; } #endif diff --git a/dom/media/webm/WebMDemuxer.cpp b/dom/media/webm/WebMDemuxer.cpp index bd8bcc61f670..2ea5ba8296eb 100644 --- a/dom/media/webm/WebMDemuxer.cpp +++ b/dom/media/webm/WebMDemuxer.cpp @@ -363,8 +363,7 @@ nsresult WebMDemuxer::ReadMetadata() { if (mInfo.mVideo.mCrypto.IsEncrypted()) { MOZ_ASSERT(mInfo.mVideo.mCrypto.mCryptoScheme == CryptoScheme::Cenc, "WebM should only use cenc scheme"); - mCrypto.AddInitData(NS_LITERAL_STRING("webm"), - mInfo.mVideo.mCrypto.mKeyId); + mCrypto.AddInitData(u"webm"_ns, mInfo.mVideo.mCrypto.mKeyId); } } else if (type == NESTEGG_TRACK_AUDIO && !mHasAudio) { nestegg_audio_params params; @@ -434,8 +433,7 @@ nsresult WebMDemuxer::ReadMetadata() { if (mInfo.mAudio.mCrypto.IsEncrypted()) { MOZ_ASSERT(mInfo.mAudio.mCrypto.mCryptoScheme == CryptoScheme::Cenc, "WebM should only use cenc scheme"); - mCrypto.AddInitData(NS_LITERAL_STRING("webm"), - mInfo.mAudio.mCrypto.mKeyId); + mCrypto.AddInitData(u"webm"_ns, mInfo.mAudio.mCrypto.mKeyId); } } } diff --git a/dom/media/webrtc/MediaEngineDefault.cpp b/dom/media/webrtc/MediaEngineDefault.cpp index e15835252b11..73a18535e352 100644 --- a/dom/media/webrtc/MediaEngineDefault.cpp +++ b/dom/media/webrtc/MediaEngineDefault.cpp @@ -57,7 +57,7 @@ static nsString DefaultVideoName() { if (NS_SUCCEEDED(rv)) { return std::move(cameraNameFromPref); } - return NS_LITERAL_STRING(u"Default Video Device"); + return u"Default Video Device"_ns; } /** @@ -84,11 +84,11 @@ MediaEngineDefaultVideoSource::~MediaEngineDefaultVideoSource() = default; nsString MediaEngineDefaultVideoSource::GetName() const { return mName; } nsCString MediaEngineDefaultVideoSource::GetUUID() const { - return NS_LITERAL_CSTRING("1041FCBD-3F12-4F7B-9E9B-1EC556DD5676"); + return "1041FCBD-3F12-4F7B-9E9B-1EC556DD5676"_ns; } nsString MediaEngineDefaultVideoSource::GetGroupId() const { - return NS_LITERAL_STRING(u"Default Video Group"); + return u"Default Video Group"_ns; } uint32_t MediaEngineDefaultVideoSource::GetBestFitnessDistance( @@ -381,15 +381,15 @@ MediaEngineDefaultAudioSource::MediaEngineDefaultAudioSource() = default; MediaEngineDefaultAudioSource::~MediaEngineDefaultAudioSource() = default; nsString MediaEngineDefaultAudioSource::GetName() const { - return NS_LITERAL_STRING(u"Default Audio Device"); + return u"Default Audio Device"_ns; } nsCString MediaEngineDefaultAudioSource::GetUUID() const { - return NS_LITERAL_CSTRING("B7CBD7C1-53EF-42F9-8353-73F61C70C092"); + return "B7CBD7C1-53EF-42F9-8353-73F61C70C092"_ns; } nsString MediaEngineDefaultAudioSource::GetGroupId() const { - return NS_LITERAL_STRING(u"Default Audio Group"); + return u"Default Audio Group"_ns; } void MediaEngineDefaultAudioSource::GetSettings( @@ -516,18 +516,18 @@ void MediaEngineDefault::EnumerateDevices( case MediaSourceEnum::Camera: { // Only supports camera video sources. See Bug 1038241. auto newSource = MakeRefPtr(); - aDevices->AppendElement(MakeRefPtr( - newSource, newSource->GetName(), - NS_ConvertUTF8toUTF16(newSource->GetUUID()), newSource->GetGroupId(), - NS_LITERAL_STRING(""))); + aDevices->AppendElement( + MakeRefPtr(newSource, newSource->GetName(), + NS_ConvertUTF8toUTF16(newSource->GetUUID()), + newSource->GetGroupId(), u""_ns)); return; } case MediaSourceEnum::Microphone: { auto newSource = MakeRefPtr(); - aDevices->AppendElement(MakeRefPtr( - newSource, newSource->GetName(), - NS_ConvertUTF8toUTF16(newSource->GetUUID()), newSource->GetGroupId(), - NS_LITERAL_STRING(""))); + aDevices->AppendElement( + MakeRefPtr(newSource, newSource->GetName(), + NS_ConvertUTF8toUTF16(newSource->GetUUID()), + newSource->GetGroupId(), u""_ns)); return; } default: diff --git a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp index 5f47452dfa59..626c19127121 100644 --- a/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp +++ b/dom/media/webrtc/MediaEngineRemoteVideoSource.cpp @@ -38,16 +38,16 @@ static Maybe GetFacingMode(const nsString& aDeviceName) { // See media/webrtc/trunk/webrtc/modules/video_capture/android/java/src/org/ // webrtc/videoengine/VideoCaptureDeviceInfoAndroid.java - if (aDeviceName.Find(NS_LITERAL_STRING("Facing back")) != kNotFound) { + if (aDeviceName.Find(u"Facing back"_ns) != kNotFound) { return Some(VideoFacingModeEnum::Environment); } - if (aDeviceName.Find(NS_LITERAL_STRING("Facing front")) != kNotFound) { + if (aDeviceName.Find(u"Facing front"_ns) != kNotFound) { return Some(VideoFacingModeEnum::User); } #endif // ANDROID #ifdef XP_MACOSX // Kludge to test user-facing cameras on OSX. - if (aDeviceName.Find(NS_LITERAL_STRING("Face")) != -1) { + if (aDeviceName.Find(u"Face"_ns) != -1) { return Some(VideoFacingModeEnum::User); } #endif @@ -55,10 +55,10 @@ static Maybe GetFacingMode(const nsString& aDeviceName) { // The cameras' name of Surface book are "Microsoft Camera Front" and // "Microsoft Camera Rear" respectively. - if (aDeviceName.Find(NS_LITERAL_STRING("Front")) != kNotFound) { + if (aDeviceName.Find(u"Front"_ns) != kNotFound) { return Some(VideoFacingModeEnum::User); } - if (aDeviceName.Find(NS_LITERAL_STRING("Rear")) != kNotFound) { + if (aDeviceName.Find(u"Rear"_ns) != kNotFound) { return Some(VideoFacingModeEnum::Environment); } #endif // WINDOWS diff --git a/dom/media/webrtc/MediaEngineTabVideoSource.cpp b/dom/media/webrtc/MediaEngineTabVideoSource.cpp index f7c2972439f8..9e8cf069a0fe 100644 --- a/dom/media/webrtc/MediaEngineTabVideoSource.cpp +++ b/dom/media/webrtc/MediaEngineTabVideoSource.cpp @@ -108,15 +108,13 @@ nsresult MediaEngineTabVideoSource::DestroyRunnable::Run() { } nsString MediaEngineTabVideoSource::GetName() const { - return NS_LITERAL_STRING(u"&getUserMedia.videoSource.tabShare;"); + return u"&getUserMedia.videoSource.tabShare;"_ns; } -nsCString MediaEngineTabVideoSource::GetUUID() const { - return NS_LITERAL_CSTRING("tab"); -} +nsCString MediaEngineTabVideoSource::GetUUID() const { return "tab"_ns; } nsString MediaEngineTabVideoSource::GetGroupId() const { - return NS_LITERAL_STRING(u"&getUserMedia.videoSource.tabShareGroup;"); + return u"&getUserMedia.videoSource.tabShareGroup;"_ns; } #define DEFAULT_TABSHARE_VIDEO_MAX_WIDTH 4096 diff --git a/dom/media/webrtc/MediaEngineWebRTC.cpp b/dom/media/webrtc/MediaEngineWebRTC.cpp index 1e463b093ab8..eb4407652b0d 100644 --- a/dom/media/webrtc/MediaEngineWebRTC.cpp +++ b/dom/media/webrtc/MediaEngineWebRTC.cpp @@ -166,7 +166,7 @@ void MediaEngineWebRTC::EnumerateVideoDevices( scaryKind || scarySource); aDevices->AppendElement(MakeRefPtr( vSource, vSource->GetName(), NS_ConvertUTF8toUTF16(vSource->GetUUID()), - vSource->GetGroupId(), NS_LITERAL_STRING(""))); + vSource->GetGroupId(), u""_ns)); } if (mHasTabVideoSource || aCapEngine == camera::BrowserEngine) { @@ -174,7 +174,7 @@ void MediaEngineWebRTC::EnumerateVideoDevices( aDevices->AppendElement(MakeRefPtr( tabVideoSource, tabVideoSource->GetName(), NS_ConvertUTF8toUTF16(tabVideoSource->GetUUID()), - tabVideoSource->GetGroupId(), NS_LITERAL_STRING(""))); + tabVideoSource->GetGroupId(), u""_ns)); } } @@ -205,7 +205,7 @@ void MediaEngineWebRTC::EnumerateMicrophoneDevices( devices[i]->MaxChannels(), mDelayAgnostic, mExtendedFilter); RefPtr device = MakeRefPtr( source, source->GetName(), NS_ConvertUTF8toUTF16(source->GetUUID()), - source->GetGroupId(), NS_LITERAL_STRING("")); + source->GetGroupId(), u""_ns); if (devices[i]->Preferred()) { #ifdef DEBUG if (!foundPreferredDevice) { @@ -246,7 +246,7 @@ void MediaEngineWebRTC::EnumerateSpeakerDevices( // If, for example, input and output are in the same device, uuid // would be the same for both which ends up to create the same // deviceIDs (in JS). - uuid.Append(NS_LITERAL_STRING("_Speaker")); + uuid.Append(u"_Speaker"_ns); nsString groupId(device->GroupID()); if (device->Preferred()) { // In windows is possible to have more than one preferred device @@ -298,7 +298,7 @@ void MediaEngineWebRTC::EnumerateDevices( aDevices->AppendElement(MakeRefPtr( audioCaptureSource, audioCaptureSource->GetName(), NS_ConvertUTF8toUTF16(audioCaptureSource->GetUUID()), - audioCaptureSource->GetGroupId(), NS_LITERAL_STRING(""))); + audioCaptureSource->GetGroupId(), u""_ns)); } else if (aMediaSource == dom::MediaSourceEnum::Microphone) { EnumerateMicrophoneDevices(aWindowId, aDevices); } diff --git a/dom/media/webrtc/MediaEngineWebRTCAudio.cpp b/dom/media/webrtc/MediaEngineWebRTCAudio.cpp index 0b67a1cb2492..612573ab4032 100644 --- a/dom/media/webrtc/MediaEngineWebRTCAudio.cpp +++ b/dom/media/webrtc/MediaEngineWebRTCAudio.cpp @@ -1165,7 +1165,7 @@ void AudioInputProcessing::DeviceChanged(MediaTrackGraphImpl* aGraph) { void AudioInputProcessing::End() { mEnded = true; } nsString MediaEngineWebRTCAudioCaptureSource::GetName() const { - return NS_LITERAL_STRING(u"AudioCapture"); + return u"AudioCapture"_ns; } nsCString MediaEngineWebRTCAudioCaptureSource::GetUUID() const { @@ -1176,7 +1176,7 @@ nsCString MediaEngineWebRTCAudioCaptureSource::GetUUID() const { rv = nsContentUtils::GenerateUUIDInPlace(uuid); if (rv.Failed()) { - return NS_LITERAL_CSTRING(""); + return ""_ns; } uuid.ToProvidedString(uuidBuffer); @@ -1187,7 +1187,7 @@ nsCString MediaEngineWebRTCAudioCaptureSource::GetUUID() const { } nsString MediaEngineWebRTCAudioCaptureSource::GetGroupId() const { - return NS_LITERAL_STRING(u"AudioCaptureGroup"); + return u"AudioCaptureGroup"_ns; } void MediaEngineWebRTCAudioCaptureSource::SetTrack( diff --git a/dom/media/webrtc/MediaTrackConstraints.cpp b/dom/media/webrtc/MediaTrackConstraints.cpp index 4f8abfd4cda8..e6a8cf5210b1 100644 --- a/dom/media/webrtc/MediaTrackConstraints.cpp +++ b/dom/media/webrtc/MediaTrackConstraints.cpp @@ -520,9 +520,9 @@ uint32_t MediaConstraintsHelper::FitnessDistance( c.mDeviceId = empty.mDeviceId; c.mGroupId = empty.mGroupId; AutoTArray, 1> devices; - devices.AppendElement(MakeRefPtr( - aMediaEngineSource, aMediaEngineSource->GetName(), NS_LITERAL_STRING(""), - NS_LITERAL_STRING(""), NS_LITERAL_STRING(""))); + devices.AppendElement(MakeRefPtr(aMediaEngineSource, + aMediaEngineSource->GetName(), + u""_ns, u""_ns, u""_ns)); return FindBadConstraint(c, devices); } diff --git a/dom/media/webrtc/RTCCertificate.cpp b/dom/media/webrtc/RTCCertificate.cpp index cf2259bbd121..8a59d83446a7 100644 --- a/dom/media/webrtc/RTCCertificate.cpp +++ b/dom/media/webrtc/RTCCertificate.cpp @@ -254,7 +254,7 @@ already_AddRefed RTCCertificate::GenerateCertificate( return nullptr; } Sequence usages; - if (!usages.AppendElement(NS_LITERAL_STRING("sign"), fallible)) { + if (!usages.AppendElement(u"sign"_ns, fallible)) { aRv.Throw(NS_ERROR_OUT_OF_MEMORY); return nullptr; } diff --git a/dom/media/webspeech/recognition/OnlineSpeechRecognitionService.cpp b/dom/media/webspeech/recognition/OnlineSpeechRecognitionService.cpp index f73e131c74c1..10cfd0760a1d 100644 --- a/dom/media/webspeech/recognition/OnlineSpeechRecognitionService.cpp +++ b/dom/media/webspeech/recognition/OnlineSpeechRecognitionService.cpp @@ -103,7 +103,7 @@ OnlineSpeechRecognitionService::OnStopRequest(nsIRequest* aRequest, if (NS_FAILED(aStatusCode)) { success = false; - errorMsg.Assign(NS_LITERAL_STRING("Error connecting to the service.")); + errorMsg.Assign(u"Error connecting to the service."_ns); errorCode = SpeechRecognitionErrorCode::Network; } else { success = true; @@ -113,7 +113,7 @@ OnlineSpeechRecognitionService::OnStopRequest(nsIRequest* aRequest, if (!parsingSuccessful) { // there's an internal server error success = false; - errorMsg.Assign(NS_LITERAL_STRING("Internal server error")); + errorMsg.Assign(u"Internal server error"_ns); errorCode = SpeechRecognitionErrorCode::Network; } else { result.Assign(root.get("status", "error").asString().c_str()); @@ -124,7 +124,7 @@ OnlineSpeechRecognitionService::OnStopRequest(nsIRequest* aRequest, confidence = root["data"][0].get("confidence", "0").asFloat(); } else { success = false; - errorMsg.Assign(NS_LITERAL_STRING("Error reading result data.")); + errorMsg.Assign(u"Error reading result data."_ns); errorCode = SpeechRecognitionErrorCode::Network; } } else { @@ -237,8 +237,7 @@ void OnlineSpeechRecognitionService::EncoderError() { } mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Audio_capture, - NS_LITERAL_STRING("Encoder error")); + SpeechRecognitionErrorCode::Audio_capture, u"Encoder error"_ns); })); } @@ -310,7 +309,7 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(NS_FAILED(rv))) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Network, NS_LITERAL_STRING("Unknown URI")); + SpeechRecognitionErrorCode::Network, u"Unknown URI"_ns); return; } @@ -325,7 +324,7 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(!window)) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Aborted, NS_LITERAL_STRING("No window")); + SpeechRecognitionErrorCode::Aborted, u"No window"_ns); return; } @@ -333,7 +332,7 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(!doc)) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Aborted, NS_LITERAL_STRING("No document")); + SpeechRecognitionErrorCode::Aborted, u"No document"_ns); } rv = NS_NewChannel(getter_AddRefs(chan), uri, doc->NodePrincipal(), secFlags, contentPolicy, nullptr, nullptr, nullptr, nullptr, @@ -341,14 +340,13 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(NS_FAILED(rv))) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Network, - NS_LITERAL_STRING("Failed to open channel")); + SpeechRecognitionErrorCode::Network, u"Failed to open channel"_ns); return; } nsCOMPtr httpChan = do_QueryInterface(chan); if (httpChan) { - rv = httpChan->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChan->SetRequestMethod("POST"_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } @@ -356,20 +354,17 @@ void OnlineSpeechRecognitionService::DoSTT() { mRecognition->GetLang(language); // Accept-Language-STT is a custom header of our backend server used to set // the language of the speech sample being submitted by the client - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Language-STT"), + rv = httpChan->SetRequestHeader("Accept-Language-STT"_ns, NS_ConvertUTF16toUTF8(language), false); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); // Tell the server to not store the transcription by default - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Store-Transcription"), - NS_LITERAL_CSTRING("0"), false); + rv = httpChan->SetRequestHeader("Store-Transcription"_ns, "0"_ns, false); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); // Tell the server to not store the sample by default - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Store-Sample"), - NS_LITERAL_CSTRING("0"), false); + rv = httpChan->SetRequestHeader("Store-Sample"_ns, "0"_ns, false); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); // Set the product tag as teh web speech api - rv = httpChan->SetRequestHeader(NS_LITERAL_CSTRING("Product-Tag"), - NS_LITERAL_CSTRING("wsa"), false); + rv = httpChan->SetRequestHeader("Product-Tag"_ns, "wsa"_ns, false); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } @@ -390,8 +385,7 @@ void OnlineSpeechRecognitionService::DoSTT() { if (!audio.SetCapacity(length, fallible)) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Audio_capture, - NS_LITERAL_STRING("Allocation error")); + SpeechRecognitionErrorCode::Audio_capture, u"Allocation error"_ns); return; } @@ -405,14 +399,12 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(NS_FAILED(rv))) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Network, - NS_LITERAL_STRING("Failed to open stream")); + SpeechRecognitionErrorCode::Network, u"Failed to open stream"_ns); return; } if (bodyStream) { - rv = uploadChan->ExplicitSetUploadStream( - bodyStream, NS_LITERAL_CSTRING("audio/ogg"), length, - NS_LITERAL_CSTRING("POST"), false); + rv = uploadChan->ExplicitSetUploadStream(bodyStream, "audio/ogg"_ns, + length, "POST"_ns, false); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); } } @@ -421,8 +413,7 @@ void OnlineSpeechRecognitionService::DoSTT() { if (NS_WARN_IF(NS_FAILED(rv))) { mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, - SpeechRecognitionErrorCode::Network, - NS_LITERAL_STRING("Internal server error")); + SpeechRecognitionErrorCode::Network, u"Internal server error"_ns); } } diff --git a/dom/media/webspeech/recognition/SpeechRecognition.cpp b/dom/media/webspeech/recognition/SpeechRecognition.cpp index 79279c469108..576f146c5075 100644 --- a/dom/media/webspeech/recognition/SpeechRecognition.cpp +++ b/dom/media/webspeech/recognition/SpeechRecognition.cpp @@ -114,7 +114,7 @@ CreateSpeechRecognitionService(nsPIDOMWindowInner* aWindow, NS_SPEECH_RECOGNITION_SERVICE_CONTRACTID_PREFIX "fake"; } else { speechRecognitionServiceCID = - NS_LITERAL_CSTRING(NS_SPEECH_RECOGNITION_SERVICE_CONTRACTID_PREFIX) + + nsLiteralCString(NS_SPEECH_RECOGNITION_SERVICE_CONTRACTID_PREFIX) + speechRecognitionService; } @@ -199,8 +199,8 @@ bool SpeechRecognition::IsAuthorized(JSContext* aCx, JSObject* aGlobal) { } uint32_t speechRecognition = nsIPermissionManager::UNKNOWN_ACTION; - rv = mgr->TestExactPermissionFromPrincipal( - principal, NS_LITERAL_CSTRING("speech-recognition"), &speechRecognition); + rv = mgr->TestExactPermissionFromPrincipal(principal, "speech-recognition"_ns, + &speechRecognition); if (NS_WARN_IF(NS_FAILED(rv))) { return false; } @@ -483,7 +483,7 @@ void SpeechRecognition::Reset() { void SpeechRecognition::ResetAndEnd() { Reset(); - DispatchTrustedEvent(NS_LITERAL_STRING("end")); + DispatchTrustedEvent(u"end"_ns); } void SpeechRecognition::WaitForAudioData(SpeechEvent* aEvent) { @@ -497,9 +497,9 @@ void SpeechRecognition::StartedAudioCapture(SpeechEvent* aEvent) { mEstimationSamples += ProcessAudioSegment(aEvent->mAudioSegment, aEvent->mTrackRate); - DispatchTrustedEvent(NS_LITERAL_STRING("audiostart")); + DispatchTrustedEvent(u"audiostart"_ns); if (mCurrentState == STATE_ESTIMATING) { - DispatchTrustedEvent(NS_LITERAL_STRING("start")); + DispatchTrustedEvent(u"start"_ns); } } @@ -535,7 +535,7 @@ void SpeechRecognition::DetectSpeech(SpeechEvent* aEvent) { if (mEndpointer.DidStartReceivingSpeech()) { mSpeechDetectionTimer->Cancel(); SetState(STATE_RECOGNIZING); - DispatchTrustedEvent(NS_LITERAL_STRING("speechstart")); + DispatchTrustedEvent(u"speechstart"_ns); } } @@ -544,7 +544,7 @@ void SpeechRecognition::WaitForSpeechEnd(SpeechEvent* aEvent) { ProcessAudioSegment(aEvent->mAudioSegment, aEvent->mTrackRate); if (mEndpointer.speech_input_complete()) { - DispatchTrustedEvent(NS_LITERAL_STRING("speechend")); + DispatchTrustedEvent(u"speechend"_ns); if (mCurrentState == STATE_RECOGNIZING) { // FIXME: StopRecordingAndRecognize should only be called for single @@ -565,8 +565,8 @@ void SpeechRecognition::NotifyFinalResult(SpeechEvent* aEvent) { init.mInterpretation = JS::NullValue(); // init.mEmma = nullptr; - RefPtr event = SpeechRecognitionEvent::Constructor( - this, NS_LITERAL_STRING("result"), init); + RefPtr event = + SpeechRecognitionEvent::Constructor(this, u"result"_ns, init); event->SetTrusted(true); DispatchEvent(*event); @@ -624,7 +624,7 @@ SpeechRecognition::StartRecording(RefPtr& aTrack) { MakeAndAddRef(this, blockerName); RefPtr shutdown = media::GetShutdownBarrier(); shutdown->AddBlocker(mShutdownBlocker, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("SpeechRecognition shutdown")); + u"SpeechRecognition shutdown"_ns); mEndpointer.StartSession(); @@ -653,7 +653,7 @@ RefPtr SpeechRecognition::StopRecording() { } mEndpointer.EndSession(); - DispatchTrustedEvent(NS_LITERAL_STRING("audioend")); + DispatchTrustedEvent(u"audioend"_ns); // Block shutdown until the speech track listener has been removed from the // MSG, as it holds a reference to us, and we reference the world, which we @@ -699,7 +699,7 @@ SpeechRecognition::Observe(nsISupports* aSubject, const char* aTopic, StateBetween(STATE_IDLE, STATE_WAITING_FOR_SPEECH)) { DispatchError(SpeechRecognition::EVENT_AUDIO_ERROR, SpeechRecognitionErrorCode::No_speech, - NS_LITERAL_STRING("No speech detected (timeout)")); + u"No speech detected (timeout)"_ns); } else if (!strcmp(aTopic, SPEECH_RECOGNITION_TEST_END_TOPIC)) { nsCOMPtr obs = services::GetObserverService(); obs->RemoveObserver(this, SPEECH_RECOGNITION_TEST_EVENT_REQUEST_TOPIC); @@ -720,7 +720,7 @@ void SpeechRecognition::ProcessTestEventRequest(nsISupports* aSubject, DispatchError( SpeechRecognition::EVENT_AUDIO_ERROR, SpeechRecognitionErrorCode::Audio_capture, // TODO different codes? - NS_LITERAL_STRING("AUDIO_ERROR test event")); + u"AUDIO_ERROR test event"_ns); } else { NS_ASSERTION(StaticPrefs::media_webspeech_test_fake_recognition_service(), "Got request for fake recognition service event, but " @@ -973,8 +973,8 @@ void SpeechRecognition::DispatchError(EventType aErrorType, RefPtr srError = new SpeechRecognitionError(nullptr, nullptr, nullptr); - srError->InitSpeechRecognitionError(NS_LITERAL_STRING("error"), true, false, - aErrorCode, aMessage); + srError->InitSpeechRecognitionError(u"error"_ns, true, false, aErrorCode, + aMessage); RefPtr event = new SpeechEvent(this, aErrorType); event->mError = srError; diff --git a/dom/media/webspeech/recognition/test/FakeSpeechRecognitionService.cpp b/dom/media/webspeech/recognition/test/FakeSpeechRecognitionService.cpp index 5e7b0193c29a..3fcea00abc68 100644 --- a/dom/media/webspeech/recognition/test/FakeSpeechRecognitionService.cpp +++ b/dom/media/webspeech/recognition/test/FakeSpeechRecognitionService.cpp @@ -84,7 +84,7 @@ FakeSpeechRecognitionService::Observe(nsISupports* aSubject, const char* aTopic, mRecognition->DispatchError( SpeechRecognition::EVENT_RECOGNITIONSERVICE_ERROR, SpeechRecognitionErrorCode::Network, // TODO different codes? - NS_LITERAL_STRING("RECOGNITIONSERVICE_ERROR test event")); + u"RECOGNITIONSERVICE_ERROR test event"_ns); } else if (eventName.EqualsLiteral("EVENT_RECOGNITIONSERVICE_FINAL_RESULT")) { RefPtr event = new SpeechEvent( @@ -105,7 +105,7 @@ FakeSpeechRecognitionService::BuildMockResultList() { SpeechRecognitionAlternative* alternative = new SpeechRecognitionAlternative(mRecognition); - alternative->mTranscript = NS_LITERAL_STRING("Mock final result"); + alternative->mTranscript = u"Mock final result"_ns; alternative->mConfidence = 0.0f; result->mItems.AppendElement(alternative); diff --git a/dom/media/webspeech/synth/SpeechSynthesis.cpp b/dom/media/webspeech/synth/SpeechSynthesis.cpp index 03753f4f81df..7ee8833b9ef7 100644 --- a/dom/media/webspeech/synth/SpeechSynthesis.cpp +++ b/dom/media/webspeech/synth/SpeechSynthesis.cpp @@ -290,7 +290,7 @@ SpeechSynthesis::Observe(nsISupports* aSubject, const char* aTopic, nsCOMPtr docShell = window ? window->GetDocShell() : nullptr; if (!nsContentUtils::ShouldResistFingerprinting(docShell)) { - DispatchTrustedEvent(NS_LITERAL_STRING("voiceschanged")); + DispatchTrustedEvent(u"voiceschanged"_ns); // If we have a pending item, and voices become available, speak it. if (!mCurrentTask && !mHoldQueue && HasVoices()) { AdvanceQueue(); diff --git a/dom/media/webspeech/synth/android/SpeechSynthesisService.cpp b/dom/media/webspeech/synth/android/SpeechSynthesisService.cpp index 6f8fe3428c53..1b6e4b6125c9 100644 --- a/dom/media/webspeech/synth/android/SpeechSynthesisService.cpp +++ b/dom/media/webspeech/synth/android/SpeechSynthesisService.cpp @@ -204,8 +204,8 @@ void SpeechSynthesisService::DispatchBoundary(jni::String::Param aUtteranceId, TimeStamp startTime = sSingleton->mTaskStartTime; sSingleton->mTaskTextOffset = aStart; DebugOnly rv = task->DispatchBoundary( - NS_LITERAL_STRING("word"), (TimeStamp::Now() - startTime).ToSeconds(), - aStart, aEnd - aStart, 1); + u"word"_ns, (TimeStamp::Now() - startTime).ToSeconds(), aStart, + aEnd - aStart, 1); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Unable to dispatch boundary"); } } diff --git a/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm b/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm index 5ed660722261..27e929b69a04 100644 --- a/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm +++ b/dom/media/webspeech/synth/cocoa/OSXSpeechSynthesizerService.mm @@ -177,8 +177,7 @@ - (void)speechSynthesizer:(NSSpeechSynthesizer*)aSender if (!mTask) { return; } - mTask->DispatchBoundary(NS_LITERAL_STRING("word"), GetTimeDurationFromStart(), mCurrentIndex, - aLength, 1); + mTask->DispatchBoundary(u"word"_ns, GetTimeDurationFromStart(), mCurrentIndex, aLength, 1); } void SpeechTaskCallback::OnError(uint32_t aIndex) { @@ -337,7 +336,7 @@ explicit EnumVoicesRunnable(OSXSpeechSynthesizerService* aSpeechService) float aRate, float aPitch, nsISpeechTask* aTask) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - MOZ_ASSERT(StringBeginsWith(aUri, NS_LITERAL_STRING("urn:moz-tts:osx:")), + MOZ_ASSERT(StringBeginsWith(aUri, u"urn:moz-tts:osx:"_ns), "OSXSpeechSynthesizerService doesn't allow this voice URI"); NSSpeechSynthesizer* synth = [[NSSpeechSynthesizer alloc] init]; diff --git a/dom/media/webspeech/synth/nsSpeechTask.cpp b/dom/media/webspeech/synth/nsSpeechTask.cpp index eb29e20f7921..8ce16ccabede 100644 --- a/dom/media/webspeech/synth/nsSpeechTask.cpp +++ b/dom/media/webspeech/synth/nsSpeechTask.cpp @@ -100,8 +100,8 @@ nsresult nsSpeechTask::DispatchStartImpl(const nsAString& aUri) { mState = STATE_SPEAKING; mUtterance->mChosenVoiceURI = aUri; - mUtterance->DispatchSpeechSynthesisEvent(NS_LITERAL_STRING("start"), 0, - nullptr, 0, EmptyString()); + mUtterance->DispatchSpeechSynthesisEvent(u"start"_ns, 0, nullptr, 0, + EmptyString()); return NS_OK; } @@ -136,8 +136,8 @@ nsresult nsSpeechTask::DispatchEndImpl(float aElapsedTime, } mState = STATE_ENDED; - utterance->DispatchSpeechSynthesisEvent(NS_LITERAL_STRING("end"), aCharIndex, - nullptr, aElapsedTime, EmptyString()); + utterance->DispatchSpeechSynthesisEvent(u"end"_ns, aCharIndex, nullptr, + aElapsedTime, EmptyString()); return NS_OK; } @@ -160,9 +160,8 @@ nsresult nsSpeechTask::DispatchPauseImpl(float aElapsedTime, mUtterance->mPaused = true; if (mState == STATE_SPEAKING) { - mUtterance->DispatchSpeechSynthesisEvent(NS_LITERAL_STRING("pause"), - aCharIndex, nullptr, aElapsedTime, - EmptyString()); + mUtterance->DispatchSpeechSynthesisEvent(u"pause"_ns, aCharIndex, nullptr, + aElapsedTime, EmptyString()); } return NS_OK; @@ -186,9 +185,8 @@ nsresult nsSpeechTask::DispatchResumeImpl(float aElapsedTime, mUtterance->mPaused = false; if (mState == STATE_SPEAKING) { - mUtterance->DispatchSpeechSynthesisEvent(NS_LITERAL_STRING("resume"), - aCharIndex, nullptr, aElapsedTime, - EmptyString()); + mUtterance->DispatchSpeechSynthesisEvent(u"resume"_ns, aCharIndex, nullptr, + aElapsedTime, EmptyString()); } return NS_OK; @@ -223,9 +221,8 @@ nsresult nsSpeechTask::DispatchErrorImpl(float aElapsedTime, } mState = STATE_ENDED; - mUtterance->DispatchSpeechSynthesisEvent(NS_LITERAL_STRING("error"), - aCharIndex, nullptr, aElapsedTime, - EmptyString()); + mUtterance->DispatchSpeechSynthesisEvent(u"error"_ns, aCharIndex, nullptr, + aElapsedTime, EmptyString()); return NS_OK; } @@ -247,7 +244,7 @@ nsresult nsSpeechTask::DispatchBoundaryImpl(const nsAString& aName, return NS_ERROR_NOT_AVAILABLE; } mUtterance->DispatchSpeechSynthesisEvent( - NS_LITERAL_STRING("boundary"), aCharIndex, + u"boundary"_ns, aCharIndex, argc ? static_cast >(aCharLength) : nullptr, aElapsedTime, aName); @@ -267,8 +264,8 @@ nsresult nsSpeechTask::DispatchMarkImpl(const nsAString& aName, if (NS_WARN_IF(mState != STATE_SPEAKING)) { return NS_ERROR_NOT_AVAILABLE; } - mUtterance->DispatchSpeechSynthesisEvent( - NS_LITERAL_STRING("mark"), aCharIndex, nullptr, aElapsedTime, aName); + mUtterance->DispatchSpeechSynthesisEvent(u"mark"_ns, aCharIndex, nullptr, + aElapsedTime, aName); return NS_OK; } diff --git a/dom/media/webspeech/synth/nsSynthVoiceRegistry.cpp b/dom/media/webspeech/synth/nsSynthVoiceRegistry.cpp index ea3994333d03..cd83ca515e3e 100644 --- a/dom/media/webspeech/synth/nsSynthVoiceRegistry.cpp +++ b/dom/media/webspeech/synth/nsSynthVoiceRegistry.cpp @@ -535,7 +535,7 @@ bool nsSynthVoiceRegistry::FindVoiceByLang(const nsAString& aLang, dashPos = end; end = start; - if (!RFindInReadable(NS_LITERAL_STRING("-"), end, dashPos)) { + if (!RFindInReadable(u"-"_ns, end, dashPos)) { break; } } @@ -582,7 +582,7 @@ VoiceData* nsSynthVoiceRegistry::FindBestMatch(const nsAString& aUri, } // Try en-US, the language of locale "C" - if (FindVoiceByLang(NS_LITERAL_STRING("en-US"), &retval)) { + if (FindVoiceByLang(u"en-US"_ns, &retval)) { LOG(LogLevel::Debug, ("nsSynthVoiceRegistry::FindBestMatch - Matched C " "locale language (en-US ~= %s)", NS_ConvertUTF16toUTF8(retval->mLang).get())); diff --git a/dom/media/webspeech/synth/windows/SapiService.cpp b/dom/media/webspeech/synth/windows/SapiService.cpp index bcd6b4d05d0a..23e1621ba8bb 100644 --- a/dom/media/webspeech/synth/windows/SapiService.cpp +++ b/dom/media/webspeech/synth/windows/SapiService.cpp @@ -131,20 +131,19 @@ void SapiCallback::OnSpeechEvent(const SPEVENT& speechEvent) { break; case SPEI_TTS_BOOKMARK: mCurrentIndex = static_cast(speechEvent.lParam) - mTextOffset; - mTask->DispatchBoundary(NS_LITERAL_STRING("mark"), - GetTickCount() - mStartingTime, mCurrentIndex, 0, - 0); + mTask->DispatchBoundary(u"mark"_ns, GetTickCount() - mStartingTime, + mCurrentIndex, 0, 0); break; case SPEI_WORD_BOUNDARY: mCurrentIndex = static_cast(speechEvent.lParam) - mTextOffset; - mTask->DispatchBoundary(NS_LITERAL_STRING("word"), - GetTickCount() - mStartingTime, mCurrentIndex, + mTask->DispatchBoundary(u"word"_ns, GetTickCount() - mStartingTime, + mCurrentIndex, static_cast(speechEvent.wParam), 1); break; case SPEI_SENTENCE_BOUNDARY: mCurrentIndex = static_cast(speechEvent.lParam) - mTextOffset; - mTask->DispatchBoundary(NS_LITERAL_STRING("sentence"), - GetTickCount() - mStartingTime, mCurrentIndex, + mTask->DispatchBoundary(u"sentence"_ns, GetTickCount() - mStartingTime, + mCurrentIndex, static_cast(speechEvent.wParam), 1); break; default: diff --git a/dom/messagechannel/MessagePort.cpp b/dom/messagechannel/MessagePort.cpp index 579b7fcb01ad..95bc04b431cf 100644 --- a/dom/messagechannel/MessagePort.cpp +++ b/dom/messagechannel/MessagePort.cpp @@ -156,9 +156,9 @@ class PostMessageRunnable final : public CancelableRunnable { return; } - event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), - CanBubble::eNo, Cancelable::eNo, value, - EmptyString(), EmptyString(), nullptr, ports); + event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo, + Cancelable::eNo, value, EmptyString(), + EmptyString(), nullptr, ports); event->SetTrusted(true); mPort->DispatchEvent(*event); @@ -879,7 +879,7 @@ void MessagePort::DispatchError() { init.mCancelable = false; RefPtr event = - MessageEvent::Constructor(this, NS_LITERAL_STRING("messageerror"), init); + MessageEvent::Constructor(this, u"messageerror"_ns, init); event->SetTrusted(true); DispatchEvent(*event); diff --git a/dom/midi/MIDIAccess.cpp b/dom/midi/MIDIAccess.cpp index 14d5b87284f1..686d59259bb7 100644 --- a/dom/midi/MIDIAccess.cpp +++ b/dom/midi/MIDIAccess.cpp @@ -126,8 +126,8 @@ void MIDIAccess::FireConnectionEvent(MIDIPort* aPort) { } } } - RefPtr event = MIDIConnectionEvent::Constructor( - this, NS_LITERAL_STRING("statechange"), init); + RefPtr event = + MIDIConnectionEvent::Constructor(this, u"statechange"_ns, init); DispatchTrustedEvent(event); } diff --git a/dom/midi/MIDIAccessManager.cpp b/dom/midi/MIDIAccessManager.cpp index 7f3dbbd10c6f..fc1230cd9a9b 100644 --- a/dom/midi/MIDIAccessManager.cpp +++ b/dom/midi/MIDIAccessManager.cpp @@ -58,7 +58,7 @@ already_AddRefed MIDIAccessManager::RequestMIDIAccess( return nullptr; } - if (!FeaturePolicyUtils::IsFeatureAllowed(doc, NS_LITERAL_STRING("midi"))) { + if (!FeaturePolicyUtils::IsFeatureAllowed(doc, u"midi"_ns)) { aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); return nullptr; } diff --git a/dom/midi/MIDIMessageEvent.cpp b/dom/midi/MIDIMessageEvent.cpp index 2bee3ee56ce4..5b57e9871945 100644 --- a/dom/midi/MIDIMessageEvent.cpp +++ b/dom/midi/MIDIMessageEvent.cpp @@ -59,7 +59,7 @@ already_AddRefed MIDIMessageEvent::Constructor( const nsTArray& aData) { MOZ_ASSERT(aOwner); RefPtr e = new MIDIMessageEvent(aOwner); - e->InitEvent(NS_LITERAL_STRING("midimessage"), false, false); + e->InitEvent(u"midimessage"_ns, false, false); e->mEvent->mTimeStamp = aReceivedTime; e->mRawData = aData.Clone(); e->SetTrusted(true); diff --git a/dom/midi/MIDIPermissionRequest.cpp b/dom/midi/MIDIPermissionRequest.cpp index d660c89b4b6f..69b00390713f 100644 --- a/dom/midi/MIDIPermissionRequest.cpp +++ b/dom/midi/MIDIPermissionRequest.cpp @@ -29,8 +29,8 @@ MIDIPermissionRequest::MIDIPermissionRequest(nsPIDOMWindowInner* aWindow, const MIDIOptions& aOptions) : ContentPermissionRequestBase( aWindow->GetDoc()->NodePrincipal(), aWindow, - NS_LITERAL_CSTRING(""), // We check prefs in a custom way here - NS_LITERAL_CSTRING("midi")), + ""_ns, // We check prefs in a custom way here + "midi"_ns), mPromise(aPromise), mNeedsSysex(aOptions.mSysex) { MOZ_ASSERT(aWindow); @@ -45,7 +45,7 @@ MIDIPermissionRequest::GetTypes(nsIArray** aTypes) { NS_ENSURE_ARG_POINTER(aTypes); nsTArray options; if (mNeedsSysex) { - options.AppendElement(NS_LITERAL_STRING("sysex")); + options.AppendElement(u"sysex"_ns); } return nsContentPermissionUtils::CreatePermissionArray(mType, options, aTypes); @@ -80,8 +80,7 @@ MIDIPermissionRequest::Run() { } // If we already have sysex perms, allow. - if (nsContentUtils::IsExactSitePermAllow(mPrincipal, - NS_LITERAL_CSTRING("midi-sysex"))) { + if (nsContentUtils::IsExactSitePermAllow(mPrincipal, "midi-sysex"_ns)) { Allow(JS::UndefinedHandleValue); return NS_OK; } diff --git a/dom/midi/MIDIPort.cpp b/dom/midi/MIDIPort.cpp index 29de586aba90..7789348bb6ea 100644 --- a/dom/midi/MIDIPort.cpp +++ b/dom/midi/MIDIPort.cpp @@ -185,8 +185,8 @@ void MIDIPort::FireStateChangeEvent() { MIDIConnectionEventInit init; init.mPort = this; - RefPtr event(MIDIConnectionEvent::Constructor( - this, NS_LITERAL_STRING("statechange"), init)); + RefPtr event( + MIDIConnectionEvent::Constructor(this, u"statechange"_ns, init)); DispatchTrustedEvent(event); } diff --git a/dom/midi/TestMIDIPlatformService.cpp b/dom/midi/TestMIDIPlatformService.cpp index 4c4d6eeb6655..51de3734c1fe 100644 --- a/dom/midi/TestMIDIPlatformService.cpp +++ b/dom/midi/TestMIDIPlatformService.cpp @@ -65,31 +65,26 @@ class QueueMessagesRunnable : public MIDIBackgroundRunnable { TestMIDIPlatformService::TestMIDIPlatformService() : mBackgroundThread(NS_GetCurrentThread()), - mControlInputPort( - NS_LITERAL_STRING("b744eebe-f7d8-499b-872b-958f63c8f522"), - NS_LITERAL_STRING("Test Control MIDI Device Input Port"), - NS_LITERAL_STRING("Test Manufacturer"), NS_LITERAL_STRING("1.0.0"), - static_cast(MIDIPortType::Input)), - mControlOutputPort( - NS_LITERAL_STRING("ab8e7fe8-c4de-436a-a960-30898a7c9a3d"), - NS_LITERAL_STRING("Test Control MIDI Device Output Port"), - NS_LITERAL_STRING("Test Manufacturer"), NS_LITERAL_STRING("1.0.0"), - static_cast(MIDIPortType::Output)), - mStateTestInputPort( - NS_LITERAL_STRING("a9329677-8588-4460-a091-9d4a7f629a48"), - NS_LITERAL_STRING("Test State MIDI Device Input Port"), - NS_LITERAL_STRING("Test Manufacturer"), NS_LITERAL_STRING("1.0.0"), - static_cast(MIDIPortType::Input)), - mStateTestOutputPort( - NS_LITERAL_STRING("478fa225-b5fc-4fa6-a543-d32d9cb651e7"), - NS_LITERAL_STRING("Test State MIDI Device Output Port"), - NS_LITERAL_STRING("Test Manufacturer"), NS_LITERAL_STRING("1.0.0"), - static_cast(MIDIPortType::Output)), - mAlwaysClosedTestOutputPort( - NS_LITERAL_STRING("f87d0c76-3c68-49a9-a44f-700f1125c07a"), - NS_LITERAL_STRING("Always Closed MIDI Device Output Port"), - NS_LITERAL_STRING("Test Manufacturer"), NS_LITERAL_STRING("1.0.0"), - static_cast(MIDIPortType::Output)), + mControlInputPort(u"b744eebe-f7d8-499b-872b-958f63c8f522"_ns, + u"Test Control MIDI Device Input Port"_ns, + u"Test Manufacturer"_ns, u"1.0.0"_ns, + static_cast(MIDIPortType::Input)), + mControlOutputPort(u"ab8e7fe8-c4de-436a-a960-30898a7c9a3d"_ns, + u"Test Control MIDI Device Output Port"_ns, + u"Test Manufacturer"_ns, u"1.0.0"_ns, + static_cast(MIDIPortType::Output)), + mStateTestInputPort(u"a9329677-8588-4460-a091-9d4a7f629a48"_ns, + u"Test State MIDI Device Input Port"_ns, + u"Test Manufacturer"_ns, u"1.0.0"_ns, + static_cast(MIDIPortType::Input)), + mStateTestOutputPort(u"478fa225-b5fc-4fa6-a543-d32d9cb651e7"_ns, + u"Test State MIDI Device Output Port"_ns, + u"Test Manufacturer"_ns, u"1.0.0"_ns, + static_cast(MIDIPortType::Output)), + mAlwaysClosedTestOutputPort(u"f87d0c76-3c68-49a9-a44f-700f1125c07a"_ns, + u"Always Closed MIDI Device Output Port"_ns, + u"Test Manufacturer"_ns, u"1.0.0"_ns, + static_cast(MIDIPortType::Output)), mIsInitialized(false) { AssertIsOnBackgroundThread(); } diff --git a/dom/network/Connection.cpp b/dom/network/Connection.cpp index 866d5f9c51bf..16314a7c883f 100644 --- a/dom/network/Connection.cpp +++ b/dom/network/Connection.cpp @@ -15,7 +15,7 @@ * We have to use macros here because our leak analysis tool things we are * leaking strings when we have |static const nsString|. Sad :( */ -#define CHANGE_EVENT_NAME NS_LITERAL_STRING("typechange") +#define CHANGE_EVENT_NAME u"typechange"_ns namespace mozilla { namespace dom { diff --git a/dom/network/ConnectionWorker.cpp b/dom/network/ConnectionWorker.cpp index 95ef946d1402..50849291c83c 100644 --- a/dom/network/ConnectionWorker.cpp +++ b/dom/network/ConnectionWorker.cpp @@ -71,9 +71,8 @@ class InitializeRunnable : public WorkerMainThreadRunnable { public: InitializeRunnable(WorkerPrivate* aWorkerPrivate, ConnectionProxy* aProxy, hal::NetworkInformation& aNetworkInfo) - : WorkerMainThreadRunnable( - aWorkerPrivate, - NS_LITERAL_CSTRING("ConnectionWorker :: Initialize")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "ConnectionWorker :: Initialize"_ns), mProxy(aProxy), mNetworkInfo(aNetworkInfo) { MOZ_ASSERT(aProxy); @@ -96,8 +95,8 @@ class ShutdownRunnable : public WorkerMainThreadRunnable { public: ShutdownRunnable(WorkerPrivate* aWorkerPrivate, ConnectionProxy* aProxy) - : WorkerMainThreadRunnable( - aWorkerPrivate, NS_LITERAL_CSTRING("ConnectionWorker :: Shutdown")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "ConnectionWorker :: Shutdown"_ns), mProxy(aProxy) { MOZ_ASSERT(aProxy); aWorkerPrivate->AssertIsOnWorkerThread(); diff --git a/dom/network/TCPServerSocket.cpp b/dom/network/TCPServerSocket.cpp index d15d7f333704..3908410b3152 100644 --- a/dom/network/TCPServerSocket.cpp +++ b/dom/network/TCPServerSocket.cpp @@ -135,7 +135,7 @@ TCPServerSocket::OnSocketAccepted(nsIServerSocket* aServer, nsCOMPtr global = GetOwnerGlobal(); RefPtr socket = TCPSocket::CreateAcceptedSocket(global, aTransport, mUseArrayBuffers); - FireEvent(NS_LITERAL_STRING("connect"), socket); + FireEvent(u"connect"_ns, socket); return NS_OK; } @@ -143,7 +143,7 @@ NS_IMETHODIMP TCPServerSocket::OnStopListening(nsIServerSocket* aServer, nsresult aStatus) { if (aStatus != NS_BINDING_ABORTED) { RefPtr event = new Event(GetOwner()); - event->InitEvent(NS_LITERAL_STRING("error"), false, false); + event->InitEvent(u"error"_ns, false, false); event->SetTrusted(true); DispatchEvent(*event); @@ -160,7 +160,7 @@ nsresult TCPServerSocket::AcceptChildSocket(TCPSocketChild* aSocketChild) { RefPtr socket = TCPSocket::CreateAcceptedSocket(global, aSocketChild, mUseArrayBuffers); NS_ENSURE_TRUE(socket, NS_ERROR_FAILURE); - FireEvent(NS_LITERAL_STRING("connect"), socket); + FireEvent(u"connect"_ns, socket); return NS_OK; } diff --git a/dom/network/TCPSocket.cpp b/dom/network/TCPSocket.cpp index dfe1ceaec48e..52a8511f8214 100644 --- a/dom/network/TCPSocket.cpp +++ b/dom/network/TCPSocket.cpp @@ -241,9 +241,9 @@ nsresult TCPSocket::Init() { AutoTArray socketTypes; if (mSsl) { - socketTypes.AppendElement(NS_LITERAL_CSTRING("ssl")); + socketTypes.AppendElement("ssl"_ns); } else { - socketTypes.AppendElement(NS_LITERAL_CSTRING("starttls")); + socketTypes.AppendElement("starttls"_ns); } nsCOMPtr transport; nsresult rv = sts->CreateTransport(socketTypes, NS_ConvertUTF16toUTF8(mHost), @@ -423,7 +423,7 @@ void TCPSocket::NotifyCopyComplete(nsresult aStatus) { // ondrain should be dispatched. if (mWaitingForDrain && !mSocketBridgeParent) { mWaitingForDrain = false; - FireEvent(NS_LITERAL_STRING("drain")); + FireEvent(u"drain"_ns); } if (mReadyState == TCPReadyState::Closing) { @@ -432,7 +432,7 @@ void TCPSocket::NotifyCopyComplete(nsresult aStatus) { mSocketOutputStream = nullptr; } mReadyState = TCPReadyState::Closed; - FireEvent(NS_LITERAL_STRING("close")); + FireEvent(u"close"_ns); } } @@ -459,7 +459,7 @@ TCPSocket::FireErrorEvent(const nsAString& aName, const nsAString& aType) { init.mMessage = aType; RefPtr event = - TCPSocketErrorEvent::Constructor(this, NS_LITERAL_STRING("error"), init); + TCPSocketErrorEvent::Constructor(this, u"error"_ns, init); MOZ_ASSERT(event); event->SetTrusted(true); DispatchEvent(*event); @@ -686,7 +686,7 @@ nsresult TCPSocket::MaybeReportErrorAndCloseIfOpen(nsresult status) { Unused << NS_WARN_IF(NS_FAILED(FireErrorEvent(errName, errorType))); } - return FireEvent(NS_LITERAL_STRING("close")); + return FireEvent(u"close"_ns); } void TCPSocket::Close() { CloseHelper(true); } @@ -894,7 +894,7 @@ TCPSocket::OnTransportStatus(nsITransport* aTransport, nsresult aStatus, mReadyState = TCPReadyState::Open; nsresult rv = CreateInputStreamPump(); NS_ENSURE_SUCCESS(rv, rv); - FireEvent(NS_LITERAL_STRING("open")); + FireEvent(u"open"_ns); return NS_OK; } @@ -942,7 +942,7 @@ TCPSocket::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream, if (!ToJSValue(cx, TypedArrayCreator(buffer), &value)) { return NS_ERROR_FAILURE; } - FireDataEvent(cx, NS_LITERAL_STRING("data"), value); + FireDataEvent(cx, u"data"_ns, value); return NS_OK; } @@ -965,7 +965,7 @@ TCPSocket::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream, if (!ToJSValue(cx, NS_ConvertASCIItoUTF16(data), &value)) { return NS_ERROR_FAILURE; } - FireDataEvent(cx, NS_LITERAL_STRING("data"), value); + FireDataEvent(cx, u"data"_ns, value); return NS_OK; } @@ -1011,7 +1011,7 @@ TCPSocket::UpdateBufferedAmount(uint32_t aBufferedAmount, if (!mBufferedAmount) { if (mWaitingForDrain) { mWaitingForDrain = false; - return FireEvent(NS_LITERAL_STRING("drain")); + return FireEvent(u"drain"_ns); } } return NS_OK; diff --git a/dom/network/TCPSocketParent.cpp b/dom/network/TCPSocketParent.cpp index ff0e9988a780..c9b2fea28718 100644 --- a/dom/network/TCPSocketParent.cpp +++ b/dom/network/TCPSocketParent.cpp @@ -153,8 +153,8 @@ mozilla::ipc::IPCResult TCPSocketParent::RecvClose() { void TCPSocketParent::FireErrorEvent(const nsAString& aName, const nsAString& aType, TCPReadyState aReadyState) { - SendEvent(NS_LITERAL_STRING("error"), - TCPError(nsString(aName), nsString(aType)), aReadyState); + SendEvent(u"error"_ns, TCPError(nsString(aName), nsString(aType)), + aReadyState); } void TCPSocketParent::FireEvent(const nsAString& aType, @@ -168,14 +168,14 @@ void TCPSocketParent::FireArrayBufferDataEvent(nsTArray& aBuffer, arr.SwapElements(aBuffer); SendableData data(arr); - SendEvent(NS_LITERAL_STRING("data"), data, aReadyState); + SendEvent(u"data"_ns, data, aReadyState); } void TCPSocketParent::FireStringDataEvent(const nsACString& aData, TCPReadyState aReadyState) { SendableData data((nsCString(aData))); - SendEvent(NS_LITERAL_STRING("data"), data, aReadyState); + SendEvent(u"data"_ns, data, aReadyState); } void TCPSocketParent::SendEvent(const nsAString& aType, CallbackData aData, diff --git a/dom/network/UDPSocket.cpp b/dom/network/UDPSocket.cpp index f74951c7231d..6366c6d5cfec 100644 --- a/dom/network/UDPSocket.cpp +++ b/dom/network/UDPSocket.cpp @@ -604,7 +604,7 @@ nsresult UDPSocket::DispatchReceivedData(const nsACString& aRemoteAddress, init.mData = jsData; RefPtr udpEvent = - UDPMessageEvent::Constructor(this, NS_LITERAL_STRING("message"), init); + UDPMessageEvent::Constructor(this, u"message"_ns, init); if (NS_WARN_IF(!udpEvent)) { return NS_ERROR_FAILURE; diff --git a/dom/network/UDPSocketParent.cpp b/dom/network/UDPSocketParent.cpp index 17355a43b244..9bba93928df0 100644 --- a/dom/network/UDPSocketParent.cpp +++ b/dom/network/UDPSocketParent.cpp @@ -530,8 +530,8 @@ void UDPSocketParent::FireInternalError(uint32_t aLineNo) { return; } - mozilla::Unused << SendCallbackError(NS_LITERAL_CSTRING("Internal error"), - NS_LITERAL_CSTRING(__FILE__), aLineNo); + mozilla::Unused << SendCallbackError("Internal error"_ns, + nsLiteralCString(__FILE__), aLineNo); } void UDPSocketParent::SendInternalError(const nsCOMPtr& aThread, diff --git a/dom/notification/Notification.cpp b/dom/notification/Notification.cpp index 67f4896529f0..54ea1420b603 100644 --- a/dom/notification/Notification.cpp +++ b/dom/notification/Notification.cpp @@ -214,9 +214,8 @@ class NotificationPermissionRequest : public ContentPermissionRequestBase, NotificationPermissionRequest(nsIPrincipal* aPrincipal, nsPIDOMWindowInner* aWindow, Promise* aPromise, NotificationPermissionCallback* aCallback) - : ContentPermissionRequestBase( - aPrincipal, aWindow, NS_LITERAL_CSTRING("notification"), - NS_LITERAL_CSTRING("desktop-notification")), + : ContentPermissionRequestBase(aPrincipal, aWindow, "notification"_ns, + "desktop-notification"_ns), mPermission(NotificationPermission::Default), mPromise(aPromise), mCallback(aCallback) { @@ -259,8 +258,7 @@ class GetPermissionRunnable final : public WorkerMainThreadRunnable { public: explicit GetPermissionRunnable(WorkerPrivate* aWorker) - : WorkerMainThreadRunnable( - aWorker, NS_LITERAL_CSTRING("Notification :: Get Permission")), + : WorkerMainThreadRunnable(aWorker, "Notification :: Get Permission"_ns), mPermission(NotificationPermission::Denied) {} bool MainThreadRun() override { @@ -487,7 +485,7 @@ NotificationPermissionRequest::Run() { nsCOMPtr doc = mWindow->GetExtantDoc(); if (doc) { nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc, + nsIScriptError::errorFlag, "DOM"_ns, doc, nsContentUtils::eDOM_PROPERTIES, "NotificationsInsecureRequestIsForbidden"); } @@ -529,7 +527,7 @@ NotificationPermissionRequest::Run() { nsCOMPtr doc = mWindow->GetExtantDoc(); if (doc) { nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc, + nsIScriptError::errorFlag, "DOM"_ns, doc, nsContentUtils::eDOM_PROPERTIES, "NotificationsCrossOriginIframeRequestIsForbidden"); } @@ -583,9 +581,9 @@ nsresult NotificationPermissionRequest::ResolvePromise() { StaticPrefs::dom_webnotifications_requireuserinteraction()) { nsCOMPtr doc = mWindow->GetExtantDoc(); if (doc) { - nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("DOM"), doc, - nsContentUtils::eDOM_PROPERTIES, "NotificationsRequireUserGesture"); + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "DOM"_ns, + doc, nsContentUtils::eDOM_PROPERTIES, + "NotificationsRequireUserGesture"); } } @@ -1014,7 +1012,7 @@ NS_IMPL_ISUPPORTS(ServiceWorkerNotificationObserver, nsIObserver) bool Notification::DispatchClickEvent() { AssertIsOnTargetThread(); RefPtr event = NS_NewDOMEvent(this, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("click"), false, true); + event->InitEvent(u"click"_ns, false, true); event->SetTrusted(true); WantsPopupControlCheck popupControlCheck(event); return DispatchEvent(*event, CallerType::System, IgnoreErrors()); @@ -1121,9 +1119,9 @@ MainThreadNotificationObserver::Observe(nsISupports* aSubject, } else if (!strcmp("alertfinished", aTopic)) { notification->UnpersistNotification(); notification->mIsClosed = true; - notification->DispatchTrustedEvent(NS_LITERAL_STRING("close")); + notification->DispatchTrustedEvent(u"close"_ns); } else if (!strcmp("alertshow", aTopic)) { - notification->DispatchTrustedEvent(NS_LITERAL_STRING("show")); + notification->DispatchTrustedEvent(u"show"_ns); } return NS_OK; } @@ -1169,11 +1167,9 @@ WorkerNotificationObserver::Observe(nsISupports* aSubject, const char* aTopic, } else if (!strcmp("alertfinished", aTopic)) { notification->UnpersistNotification(); notification->mIsClosed = true; - r = new NotificationEventWorkerRunnable(notification, - NS_LITERAL_STRING("close")); + r = new NotificationEventWorkerRunnable(notification, u"close"_ns); } else if (!strcmp("alertshow", aTopic)) { - r = new NotificationEventWorkerRunnable(notification, - NS_LITERAL_STRING("show")); + r = new NotificationEventWorkerRunnable(notification, u"show"_ns); } MOZ_ASSERT(r); @@ -1212,7 +1208,7 @@ ServiceWorkerNotificationObserver::Observe(nsISupports* aSubject, NotificationEventData data(originSuffix, NS_ConvertUTF16toUTF8(mScope), mID, mTitle, mDir, mLang, mBody, mTag, mIcon, mData, mBehavior); - Unused << cc->SendNotificationEvent(NS_LITERAL_STRING("click"), data); + Unused << cc->SendNotificationEvent(u"click"_ns, data); } return NS_OK; } @@ -1247,7 +1243,7 @@ ServiceWorkerNotificationObserver::Observe(nsISupports* aSubject, NotificationEventData data(originSuffix, NS_ConvertUTF16toUTF8(mScope), mID, mTitle, mDir, mLang, mBody, mTag, mIcon, mData, mBehavior); - Unused << cc->SendNotificationEvent(NS_LITERAL_STRING("close"), data); + Unused << cc->SendNotificationEvent(u"close"_ns, data); } return NS_OK; } @@ -1335,12 +1331,12 @@ void Notification::ShowInternal() { if (permission != NotificationPermission::Granted || !alertService) { if (mWorkerPrivate) { RefPtr r = - new NotificationEventWorkerRunnable(this, NS_LITERAL_STRING("error")); + new NotificationEventWorkerRunnable(this, u"error"_ns); if (!r->Dispatch()) { NS_WARNING("Could not dispatch event to worker notification"); } } else { - DispatchTrustedEvent(NS_LITERAL_STRING("error")); + DispatchTrustedEvent(u"error"_ns); } return; } @@ -1384,7 +1380,7 @@ void Notification::ShowInternal() { // In the case of IPC, the parent process uses the cookie to map to // nsIObserver. Thus the cookie must be unique to differentiate observers. - nsString uniqueCookie = NS_LITERAL_STRING("notification:"); + nsString uniqueCookie = u"notification:"_ns; uniqueCookie.AppendInt(sCount++); bool inPrivateBrowsing = IsInPrivateBrowsing(); @@ -1552,7 +1548,7 @@ NotificationPermission Notification::TestPermission(nsIPrincipal* aPrincipal) { } permissionManager->TestExactPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("desktop-notification"), &permission); + aPrincipal, "desktop-notification"_ns, &permission); // Convert the result to one of the enum types. switch (permission) { @@ -1839,7 +1835,7 @@ void Notification::Close() { nsresult rv = DispatchToMainThread(closeNotificationTask.forget()); if (NS_FAILED(rv)) { - DispatchTrustedEvent(NS_LITERAL_STRING("error")); + DispatchTrustedEvent(u"error"_ns); // If dispatch fails, NotificationTask will release the ref when it goes // out of scope at the end of this function. } @@ -1986,9 +1982,8 @@ class CloseNotificationRunnable final : public WorkerMainThreadRunnable { public: explicit CloseNotificationRunnable(Notification* aNotification) - : WorkerMainThreadRunnable( - aNotification->mWorkerPrivate, - NS_LITERAL_CSTRING("Notification :: Close Notification")), + : WorkerMainThreadRunnable(aNotification->mWorkerPrivate, + "Notification :: Close Notification"_ns), mNotification(aNotification), mHadObserver(false) {} @@ -2073,8 +2068,7 @@ class CheckLoadRunnable final : public WorkerMainThreadRunnable { explicit CheckLoadRunnable( WorkerPrivate* aWorker, const nsACString& aScope, const ServiceWorkerRegistrationDescriptor& aDescriptor) - : WorkerMainThreadRunnable( - aWorker, NS_LITERAL_CSTRING("Notification :: Check Load")), + : WorkerMainThreadRunnable(aWorker, "Notification :: Check Load"_ns), mRv(NS_ERROR_DOM_SECURITY_ERR), mScope(aScope), mDescriptor(aDescriptor) {} @@ -2223,7 +2217,7 @@ already_AddRefed Notification::CreateAndShow( notification->DispatchToMainThread(showNotificationTask.forget()); if (NS_WARN_IF(NS_FAILED(rv))) { - notification->DispatchTrustedEvent(NS_LITERAL_STRING("error")); + notification->DispatchTrustedEvent(u"error"_ns); } return notification.forget(); @@ -2237,8 +2231,7 @@ nsresult Notification::RemovePermission(nsIPrincipal* aPrincipal) { if (!permissionManager) { return NS_ERROR_FAILURE; } - permissionManager->RemoveFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("desktop-notification")); + permissionManager->RemoveFromPrincipal(aPrincipal, "desktop-notification"_ns); return NS_OK; } diff --git a/dom/notification/Notification.h b/dom/notification/Notification.h index dceadeeea80a..9981e551dacf 100644 --- a/dom/notification/Notification.h +++ b/dom/notification/Notification.h @@ -259,11 +259,11 @@ class Notification : public DOMEventTargetHelper, static const nsString DirectionToString(NotificationDirection aDirection) { switch (aDirection) { case NotificationDirection::Ltr: - return NS_LITERAL_STRING("ltr"); + return u"ltr"_ns; case NotificationDirection::Rtl: - return NS_LITERAL_STRING("rtl"); + return u"rtl"_ns; default: - return NS_LITERAL_STRING("auto"); + return u"auto"_ns; } } diff --git a/dom/payments/BasicCardPayment.cpp b/dom/payments/BasicCardPayment.cpp index 8c616ee3366d..587766e2dd77 100644 --- a/dom/payments/BasicCardPayment.cpp +++ b/dom/payments/BasicCardPayment.cpp @@ -15,15 +15,11 @@ namespace mozilla { namespace dom { namespace { bool IsValidNetwork(const nsAString& aNetwork) { - return aNetwork.Equals(NS_LITERAL_STRING("amex")) || - aNetwork.Equals(NS_LITERAL_STRING("cartebancaire")) || - aNetwork.Equals(NS_LITERAL_STRING("diners")) || - aNetwork.Equals(NS_LITERAL_STRING("discover")) || - aNetwork.Equals(NS_LITERAL_STRING("jcb")) || - aNetwork.Equals(NS_LITERAL_STRING("mastercard")) || - aNetwork.Equals(NS_LITERAL_STRING("mir")) || - aNetwork.Equals(NS_LITERAL_STRING("unionpay")) || - aNetwork.Equals(NS_LITERAL_STRING("visa")); + return aNetwork.Equals(u"amex"_ns) || aNetwork.Equals(u"cartebancaire"_ns) || + aNetwork.Equals(u"diners"_ns) || aNetwork.Equals(u"discover"_ns) || + aNetwork.Equals(u"jcb"_ns) || aNetwork.Equals(u"mastercard"_ns) || + aNetwork.Equals(u"mir"_ns) || aNetwork.Equals(u"unionpay"_ns) || + aNetwork.Equals(u"visa"_ns); } } // end of namespace @@ -39,7 +35,7 @@ already_AddRefed BasicCardService::GetService() { } bool BasicCardService::IsBasicCardPayment(const nsAString& aSupportedMethods) { - return aSupportedMethods.Equals(NS_LITERAL_STRING("basic-card")); + return aSupportedMethods.Equals(u"basic-card"_ns); } bool BasicCardService::IsValidBasicCardRequest(JSContext* aCx, JSObject* aData, @@ -58,8 +54,7 @@ bool BasicCardService::IsValidBasicCardRequest(JSContext* aCx, JSObject* aData, for (const nsString& network : request.mSupportedNetworks) { if (!IsValidNetwork(network)) { - aErrorMsg.Assign(network + - NS_LITERAL_STRING(" is not an valid network.")); + aErrorMsg.Assign(network + u" is not an valid network."_ns); return false; } } diff --git a/dom/payments/PaymentActionResponse.cpp b/dom/payments/PaymentActionResponse.cpp index 86416b1e9198..3e79b702e096 100644 --- a/dom/payments/PaymentActionResponse.cpp +++ b/dom/payments/PaymentActionResponse.cpp @@ -36,7 +36,7 @@ PaymentResponseData::Init(const uint32_t aType) { NS_IMPL_ISUPPORTS_INHERITED(GeneralResponseData, PaymentResponseData, nsIGeneralResponseData) -GeneralResponseData::GeneralResponseData() : mData(NS_LITERAL_STRING("{}")) { +GeneralResponseData::GeneralResponseData() : mData(u"{}"_ns) { Init(nsIPaymentResponseData::GENERAL_RESPONSE); } @@ -370,8 +370,7 @@ MethodChangeDetails::Init(const uint32_t aType) { NS_IMPL_ISUPPORTS_INHERITED(GeneralMethodChangeDetails, MethodChangeDetails, nsIGeneralChangeDetails) -GeneralMethodChangeDetails::GeneralMethodChangeDetails() - : mDetails(NS_LITERAL_STRING("{}")) { +GeneralMethodChangeDetails::GeneralMethodChangeDetails() : mDetails(u"{}"_ns) { Init(nsIMethodChangeDetails::GENERAL_DETAILS); } diff --git a/dom/payments/PaymentRequest.cpp b/dom/payments/PaymentRequest.cpp index f36bdf6aa7af..79dd4e7c8459 100644 --- a/dom/payments/PaymentRequest.cpp +++ b/dom/payments/PaymentRequest.cpp @@ -477,8 +477,7 @@ void PaymentRequest::IsValidDetailsInit(const PaymentDetailsInit& aDetails, const bool aRequestShipping, ErrorResult& aRv) { // Check the amount.value and amount.currency of detail.total - IsValidCurrencyAmount(NS_LITERAL_STRING("details.total"), - aDetails.mTotal.mAmount, + IsValidCurrencyAmount(u"details.total"_ns, aDetails.mTotal.mAmount, true, // isTotalItem aRv); if (aRv.Failed()) { @@ -492,8 +491,7 @@ void PaymentRequest::IsValidDetailsUpdate(const PaymentDetailsUpdate& aDetails, ErrorResult& aRv) { // Check the amount.value and amount.currency of detail.total if (aDetails.mTotal.WasPassed()) { - IsValidCurrencyAmount(NS_LITERAL_STRING("details.total"), - aDetails.mTotal.Value().mAmount, + IsValidCurrencyAmount(u"details.total"_ns, aDetails.mTotal.Value().mAmount, true, // isTotalItem aRv); if (aRv.Failed()) { @@ -525,7 +523,7 @@ void PaymentRequest::IsValidDetailsBase(const PaymentDetailsBase& aDetails, aDetails.mShippingOptions.Value(); nsTArray seenIDs; for (const PaymentShippingOption& shippingOption : shippingOptions) { - IsValidCurrencyAmount(NS_LITERAL_STRING("details.shippingOptions"), + IsValidCurrencyAmount(u"details.shippingOptions"_ns, shippingOption.mAmount, false, // isTotalItem aRv); @@ -554,7 +552,7 @@ void PaymentRequest::IsValidDetailsBase(const PaymentDetailsBase& aDetails, return; } if (modifier.mTotal.WasPassed()) { - IsValidCurrencyAmount(NS_LITERAL_STRING("details.modifiers.total"), + IsValidCurrencyAmount(u"details.modifiers.total"_ns, modifier.mTotal.Value().mAmount, true, // isTotalItem aRv); @@ -602,8 +600,7 @@ already_AddRefed PaymentRequest::Constructor( return nullptr; } - if (!FeaturePolicyUtils::IsFeatureAllowed(doc, - NS_LITERAL_STRING("payment"))) { + if (!FeaturePolicyUtils::IsFeatureAllowed(doc, u"payment"_ns)) { aRv.ThrowSecurityError( "Document's Feature Policy does not allow to create a PaymentRequest"); return nullptr; @@ -737,10 +734,10 @@ already_AddRefed PaymentRequest::Show( Document* doc = win->GetExtantDoc(); if (!UserActivation::IsHandlingUserInput()) { - nsString msg = NS_LITERAL_STRING( - "User activation is now required to call PaymentRequest.show()"); + nsString msg = nsLiteralString( + u"User activation is now required to call PaymentRequest.show()"); nsContentUtils::ReportToConsoleNonLocalized( - msg, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"), doc); + msg, nsIScriptError::warningFlag, "Security"_ns, doc); if (StaticPrefs::dom_payments_request_user_interaction_required()) { aRv.ThrowSecurityError(NS_ConvertUTF16toUTF8(msg)); return nullptr; @@ -1036,9 +1033,8 @@ nsresult PaymentRequest::DispatchPaymentMethodChangeEvent( init.mCancelable = false; RefPtr event = - PaymentMethodChangeEvent::Constructor( - this, NS_LITERAL_STRING("paymentmethodchange"), init, aMethodName, - aMethodDetails); + PaymentMethodChangeEvent::Constructor(this, u"paymentmethodchange"_ns, + init, aMethodName, aMethodDetails); event->SetTrusted(true); event->SetRequest(this); @@ -1069,7 +1065,7 @@ nsresult PaymentRequest::UpdateShippingAddress( aRegionCode, aCity, aDependentLocality, aPostalCode, aSortingCode, aOrganization, aRecipient, aPhone); // Fire shippingaddresschange event - return DispatchUpdateEvent(NS_LITERAL_STRING("shippingaddresschange")); + return DispatchUpdateEvent(u"shippingaddresschange"_ns); } void PaymentRequest::SetShippingOption(const nsAString& aShippingOption) { @@ -1085,7 +1081,7 @@ nsresult PaymentRequest::UpdateShippingOption( mShippingOption = aShippingOption; // Fire shippingaddresschange event - return DispatchUpdateEvent(NS_LITERAL_STRING("shippingoptionchange")); + return DispatchUpdateEvent(u"shippingoptionchange"_ns); } nsresult PaymentRequest::UpdatePaymentMethod( diff --git a/dom/payments/PaymentRequestManager.cpp b/dom/payments/PaymentRequestManager.cpp index 22ca04d3e1aa..22a65ac7de2d 100644 --- a/dom/payments/PaymentRequestManager.cpp +++ b/dom/payments/PaymentRequestManager.cpp @@ -551,7 +551,7 @@ void PaymentRequestManager::AbortPayment(PaymentRequest* aRequest, void PaymentRequestManager::CompletePayment(PaymentRequest* aRequest, const PaymentComplete& aComplete, ErrorResult& aRv, bool aTimedOut) { - nsString completeStatusString(NS_LITERAL_STRING("unknown")); + nsString completeStatusString(u"unknown"_ns); if (aTimedOut) { completeStatusString.AssignLiteral("timeout"); } else { diff --git a/dom/payments/PaymentRequestService.cpp b/dom/payments/PaymentRequestService.cpp index 4bf4dd163f83..55821f2c1bd7 100644 --- a/dom/payments/PaymentRequestService.cpp +++ b/dom/payments/PaymentRequestService.cpp @@ -301,7 +301,7 @@ nsresult PaymentRequestService::RequestPayment( if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - if (completeStatus.Equals(NS_LITERAL_STRING("initial"))) { + if (completeStatus.Equals(u"initial"_ns)) { request->SetCompleteStatus(EmptyString()); } MOZ_ASSERT(mShowingRequest && mShowingRequest == request); @@ -544,7 +544,7 @@ nsresult PaymentRequestService::ShowPayment(const nsAString& aRequestId, MOZ_ASSERT(request); request->SetState(payments::PaymentRequest::eInteractive); if (aIsUpdating) { - request->SetCompleteStatus(NS_LITERAL_STRING("initial")); + request->SetCompleteStatus(u"initial"_ns); } if (mShowingRequest || !CanMakePayment(aRequestId)) { diff --git a/dom/payments/PaymentResponse.cpp b/dom/payments/PaymentResponse.cpp index 73cdc9243e16..bc11819cae0c 100644 --- a/dom/payments/PaymentResponse.cpp +++ b/dom/payments/PaymentResponse.cpp @@ -435,7 +435,7 @@ nsresult PaymentResponse::UpdatePayerDetail(const nsAString& aPayerName, if (options.mRequestPayerPhone) { mPayerPhone = aPayerPhone; } - return DispatchUpdateEvent(NS_LITERAL_STRING("payerdetailchange")); + return DispatchUpdateEvent(u"payerdetailchange"_ns); } nsresult PaymentResponse::DispatchUpdateEvent(const nsAString& aType) { diff --git a/dom/performance/Performance.cpp b/dom/performance/Performance.cpp index 2140571a5791..0843cd415834 100644 --- a/dom/performance/Performance.cpp +++ b/dom/performance/Performance.cpp @@ -232,7 +232,7 @@ void Performance::Mark(const nsAString& aName, ErrorResult& aRv) { } void Performance::ClearMarks(const Optional& aName) { - ClearUserEntries(aName, NS_LITERAL_STRING("mark")); + ClearUserEntries(aName, u"mark"_ns); } DOMHighResTimeStamp Performance::ResolveTimestampFromName( @@ -328,7 +328,7 @@ void Performance::Measure(const nsAString& aName, } void Performance::ClearMeasures(const Optional& aName) { - ClearUserEntries(aName, NS_LITERAL_STRING("measure")); + ClearUserEntries(aName, u"measure"_ns); } void Performance::LogEntry(PerformanceEntry* aEntry, @@ -354,8 +354,7 @@ void Performance::TimingNotification(PerformanceEntry* aEntry, init.mOrigin = NS_ConvertUTF8toUTF16(aOwner.BeginReading()); RefPtr perfEntryEvent = - PerformanceEntryEvent::Constructor( - this, NS_LITERAL_STRING("performanceentry"), init); + PerformanceEntryEvent::Constructor(this, u"performanceentry"_ns, init); nsCOMPtr et = do_QueryInterface(GetOwner()); if (et) { diff --git a/dom/performance/PerformanceMainThread.cpp b/dom/performance/PerformanceMainThread.cpp index c38c616d955d..469183577eba 100644 --- a/dom/performance/PerformanceMainThread.cpp +++ b/dom/performance/PerformanceMainThread.cpp @@ -117,7 +117,7 @@ PerformanceTiming* PerformanceMainThread::Timing() { void PerformanceMainThread::DispatchBufferFullEvent() { RefPtr event = NS_NewDOMEvent(this, nullptr, nullptr); // it bubbles, and it isn't cancelable - event->InitEvent(NS_LITERAL_STRING("resourcetimingbufferfull"), true, false); + event->InitEvent(u"resourcetimingbufferfull"_ns, true, false); event->SetTrusted(true); DispatchEvent(*event); } diff --git a/dom/performance/PerformanceMark.cpp b/dom/performance/PerformanceMark.cpp index bb14818d5548..3cd3ecf2fc9e 100644 --- a/dom/performance/PerformanceMark.cpp +++ b/dom/performance/PerformanceMark.cpp @@ -12,8 +12,7 @@ using namespace mozilla::dom; PerformanceMark::PerformanceMark(nsISupports* aParent, const nsAString& aName, DOMHighResTimeStamp aStartTime) - : PerformanceEntry(aParent, aName, NS_LITERAL_STRING("mark")), - mStartTime(aStartTime) {} + : PerformanceEntry(aParent, aName, u"mark"_ns), mStartTime(aStartTime) {} PerformanceMark::~PerformanceMark() = default; diff --git a/dom/performance/PerformanceMeasure.cpp b/dom/performance/PerformanceMeasure.cpp index cd366f9e1971..81f2999facc0 100644 --- a/dom/performance/PerformanceMeasure.cpp +++ b/dom/performance/PerformanceMeasure.cpp @@ -14,7 +14,7 @@ PerformanceMeasure::PerformanceMeasure(nsISupports* aParent, const nsAString& aName, DOMHighResTimeStamp aStartTime, DOMHighResTimeStamp aEndTime) - : PerformanceEntry(aParent, aName, NS_LITERAL_STRING("measure")), + : PerformanceEntry(aParent, aName, u"measure"_ns), mStartTime(aStartTime), mDuration(aEndTime - aStartTime) {} diff --git a/dom/performance/PerformanceNavigationTiming.h b/dom/performance/PerformanceNavigationTiming.h index f891baca8261..602889273bee 100644 --- a/dom/performance/PerformanceNavigationTiming.h +++ b/dom/performance/PerformanceNavigationTiming.h @@ -31,8 +31,8 @@ class PerformanceNavigationTiming final : public PerformanceResourceTiming { Performance* aPerformance, const nsAString& aName) : PerformanceResourceTiming(std::move(aPerformanceTiming), aPerformance, aName) { - SetEntryType(NS_LITERAL_STRING("navigation")); - SetInitiatorType(NS_LITERAL_STRING("navigation")); + SetEntryType(u"navigation"_ns); + SetInitiatorType(u"navigation"_ns); } DOMHighResTimeStamp Duration() const override { diff --git a/dom/performance/PerformanceObserver.cpp b/dom/performance/PerformanceObserver.cpp index 932dff56e3c3..bc69e5accea4 100644 --- a/dom/performance/PerformanceObserver.cpp +++ b/dom/performance/PerformanceObserver.cpp @@ -149,9 +149,9 @@ void PerformanceObserver::ReportUnsupportedTypesErrorToConsole( nsCOMPtr ownerWindow = do_QueryInterface(mOwner); Document* document = ownerWindow->GetExtantDoc(); AutoTArray params = {aInvalidTypes}; - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), document, - nsContentUtils::eDOM_PROPERTIES, msgId, params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + document, nsContentUtils::eDOM_PROPERTIES, + msgId, params); } } diff --git a/dom/performance/PerformanceResourceTiming.cpp b/dom/performance/PerformanceResourceTiming.cpp index 954d5f5674d3..c6fa1224782d 100644 --- a/dom/performance/PerformanceResourceTiming.cpp +++ b/dom/performance/PerformanceResourceTiming.cpp @@ -27,8 +27,7 @@ NS_IMPL_RELEASE_INHERITED(PerformanceResourceTiming, PerformanceEntry) PerformanceResourceTiming::PerformanceResourceTiming( UniquePtr&& aPerformanceTiming, Performance* aPerformance, const nsAString& aName) - : PerformanceEntry(aPerformance->GetParentObject(), aName, - NS_LITERAL_STRING("resource")), + : PerformanceEntry(aPerformance->GetParentObject(), aName, u"resource"_ns), mTimingData(std::move(aPerformanceTiming)), mPerformance(aPerformance) { MOZ_ASSERT(aPerformance, "Parent performance object should be provided"); diff --git a/dom/performance/PerformanceTiming.cpp b/dom/performance/PerformanceTiming.cpp index 8cccc2e94233..b89ddf69d7ee 100644 --- a/dom/performance/PerformanceTiming.cpp +++ b/dom/performance/PerformanceTiming.cpp @@ -51,7 +51,7 @@ PerformanceTimingData* PerformanceTimingData::Create( // If the initiator type had no valid value, then set it to the default // ("other") value. if (aInitiatorType.IsEmpty()) { - aInitiatorType = NS_LITERAL_STRING("other"); + aInitiatorType = u"other"_ns; } // According to the spec, "The name attribute must return the resolved URL diff --git a/dom/permission/PermissionStatus.cpp b/dom/permission/PermissionStatus.cpp index 57bee07ac017..1a872082c3d4 100644 --- a/dom/permission/PermissionStatus.cpp +++ b/dom/permission/PermissionStatus.cpp @@ -34,7 +34,7 @@ PermissionStatus::PermissionStatus(nsPIDOMWindowInner* aWindow, : DOMEventTargetHelper(aWindow), mName(aName), mState(PermissionState::Denied) { - KeepAliveIfHasListenersFor(NS_LITERAL_STRING("change")); + KeepAliveIfHasListenersFor(u"change"_ns); } nsresult PermissionStatus::Init() { @@ -115,14 +115,14 @@ void PermissionStatus::PermissionChanged() { auto oldState = mState; UpdateState(); if (mState != oldState) { - RefPtr eventDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("change"), CanBubble::eNo); + RefPtr eventDispatcher = + new AsyncEventDispatcher(this, u"change"_ns, CanBubble::eNo); eventDispatcher->PostDOMEvent(); } } void PermissionStatus::DisconnectFromOwner() { - IgnoreKeepAliveIfHasListenersFor(NS_LITERAL_STRING("change")); + IgnoreKeepAliveIfHasListenersFor(u"change"_ns); if (mObserver) { mObserver->RemoveSink(this); diff --git a/dom/permission/PermissionUtils.cpp b/dom/permission/PermissionUtils.cpp index a0c853becf3d..4621aadf6a6d 100644 --- a/dom/permission/PermissionUtils.cpp +++ b/dom/permission/PermissionUtils.cpp @@ -11,11 +11,11 @@ namespace dom { static const nsLiteralCString kPermissionTypes[] = { // clang-format off - NS_LITERAL_CSTRING("geo"), - NS_LITERAL_CSTRING("desktop-notification"), + "geo"_ns, + "desktop-notification"_ns, // Alias `push` to `desktop-notification`. - NS_LITERAL_CSTRING("desktop-notification"), - NS_LITERAL_CSTRING("persistent-storage") + "desktop-notification"_ns, + "persistent-storage"_ns // clang-format on }; diff --git a/dom/plugins/base/PluginFinder.cpp b/dom/plugins/base/PluginFinder.cpp index 4e1c1fd53698..dfac7b052567 100644 --- a/dom/plugins/base/PluginFinder.cpp +++ b/dom/plugins/base/PluginFinder.cpp @@ -44,7 +44,7 @@ static const char* kPluginRegistryVersion = "0.19"; StaticRefPtr sPluginRegFile; -#define kPluginRegistryFilename NS_LITERAL_CSTRING("pluginreg.dat") +#define kPluginRegistryFilename "pluginreg.dat"_ns #define NS_ITERATIVE_UNREF_LIST(type_, list_, mNext_) \ { \ @@ -142,12 +142,10 @@ NS_IMETHODIMP PluginFinder::GetState(nsIPropertyBag** aBagOut) { if (NS_WARN_IF(!propertyBag)) { return NS_ERROR_OUT_OF_MEMORY; } - propertyBag->SetPropertyAsBool(NS_LITERAL_STRING("Finding"), - !mFinishedFinding); - propertyBag->SetPropertyAsBool(NS_LITERAL_STRING("CreatingList"), - mCreateList); - propertyBag->SetPropertyAsBool(NS_LITERAL_STRING("FlashOnly"), mFlashOnly); - propertyBag->SetPropertyAsBool(NS_LITERAL_STRING("HavePlugins"), !!mPlugins); + propertyBag->SetPropertyAsBool(u"Finding"_ns, !mFinishedFinding); + propertyBag->SetPropertyAsBool(u"CreatingList"_ns, mCreateList); + propertyBag->SetPropertyAsBool(u"FlashOnly"_ns, mFlashOnly); + propertyBag->SetPropertyAsBool(u"HavePlugins"_ns, !!mPlugins); propertyBag.forget(aBagOut); return NS_OK; } @@ -968,7 +966,7 @@ nsresult PluginFinder::DeterminePluginDirs() { rv = dirService->Get(NS_APP_USER_PROFILE_50_DIR, NS_GET_IID(nsIFile), getter_AddRefs(profDir)); if (NS_SUCCEEDED(rv)) { - profDir->Append(NS_LITERAL_STRING("plugins")); + profDir->Append(u"plugins"_ns); mPluginDirs.AppendElement(profDir); } } diff --git a/dom/plugins/base/nsNPAPIPluginInstance.cpp b/dom/plugins/base/nsNPAPIPluginInstance.cpp index 5f1e9baddd07..c011cd038dfc 100644 --- a/dom/plugins/base/nsNPAPIPluginInstance.cpp +++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp @@ -261,8 +261,7 @@ nsresult nsNPAPIPluginInstance::Start() { mCachedParamValues[i] = ToNewUTF8String(attributes[i].mValue); } - mCachedParamNames[attributes.Length()] = - ToNewUTF8String(NS_LITERAL_STRING("PARAM")); + mCachedParamNames[attributes.Length()] = ToNewUTF8String(u"PARAM"_ns); mCachedParamValues[attributes.Length()] = nullptr; for (uint32_t i = 0, pos = attributes.Length() + 1; i < params.Length(); diff --git a/dom/plugins/base/nsPluginDirServiceProvider.cpp b/dom/plugins/base/nsPluginDirServiceProvider.cpp index 87236548027e..5b379c8448fc 100644 --- a/dom/plugins/base/nsPluginDirServiceProvider.cpp +++ b/dom/plugins/base/nsPluginDirServiceProvider.cpp @@ -26,9 +26,8 @@ using namespace mozilla; do_CreateInstance("@mozilla.org/windows-registry-key;1"); NS_ENSURE_TRUE(regKey, NS_ERROR_FAILURE); - nsresult rv = - regKey->Open(aKey, NS_LITERAL_STRING("Software\\MozillaPlugins"), - nsIWindowsRegKey::ACCESS_READ); + nsresult rv = regKey->Open(aKey, u"Software\\MozillaPlugins"_ns, + nsIWindowsRegKey::ACCESS_READ); if (NS_FAILED(rv)) { return rv; } @@ -45,7 +44,7 @@ using namespace mozilla; getter_AddRefs(childKey)); if (NS_SUCCEEDED(rv) && childKey) { nsAutoString path; - rv = childKey->ReadStringValue(NS_LITERAL_STRING("Path"), path); + rv = childKey->ReadStringValue(u"Path"_ns, path); if (NS_SUCCEEDED(rv)) { // We deliberately do not do any further checks here on whether // these are actually directories, whether they even exist, or diff --git a/dom/plugins/base/nsPluginHost.cpp b/dom/plugins/base/nsPluginHost.cpp index 9368fe0f0bf7..d09643ac571c 100644 --- a/dom/plugins/base/nsPluginHost.cpp +++ b/dom/plugins/base/nsPluginHost.cpp @@ -1839,7 +1839,7 @@ static void WatchRegKey(uint32_t aRoot, nsCOMPtr& aKey) { return; } nsresult rv = aKey->Open( - aRoot, NS_LITERAL_STRING("Software\\MozillaPlugins"), + aRoot, u"Software\\MozillaPlugins"_ns, nsIWindowsRegKey::ACCESS_READ | nsIWindowsRegKey::ACCESS_NOTIFY); if (NS_FAILED(rv)) { aKey = nullptr; @@ -1952,9 +1952,8 @@ nsresult nsPluginHost::LoadPlugins() { nsCOMPtr shutdownPhase = GetProfileChangeTeardownPhase(); if (shutdownPhase) { - rv = - shutdownPhase->AddBlocker(mPendingFinder, NS_LITERAL_STRING(__FILE__), - __LINE__, NS_LITERAL_STRING("")); + rv = shutdownPhase->AddBlocker( + mPendingFinder, NS_LITERAL_STRING(__FILE__), __LINE__, u""_ns); mAddedFinderShutdownBlocker = NS_SUCCEEDED(rv); } @@ -2755,21 +2754,20 @@ void nsPluginHost::PluginCrashed(nsNPAPIPlugin* aPlugin, if (!NS_WARN_IF(!library)) { library->GetRunID(&runID); } - propbag->SetPropertyAsUint32(NS_LITERAL_STRING("runID"), runID); + propbag->SetPropertyAsUint32(u"runID"_ns, runID); nsCString pluginName; crashedPluginTag->GetName(pluginName); - propbag->SetPropertyAsAString(NS_LITERAL_STRING("pluginName"), + propbag->SetPropertyAsAString(u"pluginName"_ns, NS_ConvertUTF8toUTF16(pluginName)); - propbag->SetPropertyAsAString(NS_LITERAL_STRING("pluginDumpID"), - aPluginDumpID); - propbag->SetPropertyAsACString(NS_LITERAL_STRING("additionalMinidumps"), + propbag->SetPropertyAsAString(u"pluginDumpID"_ns, aPluginDumpID); + propbag->SetPropertyAsACString(u"additionalMinidumps"_ns, aAdditionalMinidumps); - propbag->SetPropertyAsBool(NS_LITERAL_STRING("submittedCrashReport"), + propbag->SetPropertyAsBool(u"submittedCrashReport"_ns, submittedCrashReport); obsService->NotifyObservers(propbag, "plugin-crashed", nullptr); // see if an observer submitted a crash report. - propbag->GetPropertyAsBool(NS_LITERAL_STRING("submittedCrashReport"), + propbag->GetPropertyAsBool(u"submittedCrashReport"_ns, &submittedCrashReport); } diff --git a/dom/plugins/base/nsPluginInstanceOwner.cpp b/dom/plugins/base/nsPluginInstanceOwner.cpp index a0e4624d1d24..5fbaeb7646d2 100644 --- a/dom/plugins/base/nsPluginInstanceOwner.cpp +++ b/dom/plugins/base/nsPluginInstanceOwner.cpp @@ -113,8 +113,7 @@ class AsyncPaintWaitEvent : public Runnable { NS_IMETHOD Run() override { nsContentUtils::DispatchEventOnlyToChrome( mContent->OwnerDoc(), mContent, - mFinished ? NS_LITERAL_STRING("MozPaintWaitFinished") - : NS_LITERAL_STRING("MozPaintWait"), + mFinished ? u"MozPaintWaitFinished"_ns : u"MozPaintWait"_ns, CanBubble::eYes, Cancelable::eYes); return NS_OK; } @@ -1934,9 +1933,8 @@ void nsPluginInstanceOwner::PerformDelayedBlurs() { nsCOMPtr windowRoot = content->OwnerDoc()->GetWindow()->GetTopWindowRoot(); nsContentUtils::DispatchEventOnlyToChrome( - content->OwnerDoc(), windowRoot, - NS_LITERAL_STRING("MozPerformDelayedBlur"), CanBubble::eNo, - Cancelable::eNo, nullptr); + content->OwnerDoc(), windowRoot, u"MozPerformDelayedBlur"_ns, + CanBubble::eNo, Cancelable::eNo, nullptr); } #endif @@ -2429,32 +2427,30 @@ nsresult nsPluginInstanceOwner::Destroy() { mCXMenuListener = nullptr; } - content->RemoveEventListener(NS_LITERAL_STRING("focus"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("blur"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("mouseup"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("mousemove"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("click"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("dblclick"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("mouseover"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("mouseout"), this, false); - content->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, true); - content->RemoveSystemEventListener(NS_LITERAL_STRING("keypress"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("drop"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("drag"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragenter"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragover"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragleave"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragexit"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragstart"), this, true); - content->RemoveEventListener(NS_LITERAL_STRING("dragend"), this, true); - content->RemoveSystemEventListener(NS_LITERAL_STRING("compositionstart"), - this, true); - content->RemoveSystemEventListener(NS_LITERAL_STRING("compositionend"), this, - true); - content->RemoveSystemEventListener(NS_LITERAL_STRING("text"), this, true); + content->RemoveEventListener(u"focus"_ns, this, false); + content->RemoveEventListener(u"blur"_ns, this, false); + content->RemoveEventListener(u"mouseup"_ns, this, false); + content->RemoveEventListener(u"mousedown"_ns, this, false); + content->RemoveEventListener(u"mousemove"_ns, this, false); + content->RemoveEventListener(u"click"_ns, this, false); + content->RemoveEventListener(u"dblclick"_ns, this, false); + content->RemoveEventListener(u"mouseover"_ns, this, false); + content->RemoveEventListener(u"mouseout"_ns, this, false); + content->RemoveEventListener(u"keypress"_ns, this, true); + content->RemoveSystemEventListener(u"keypress"_ns, this, true); + content->RemoveEventListener(u"keydown"_ns, this, true); + content->RemoveEventListener(u"keyup"_ns, this, true); + content->RemoveEventListener(u"drop"_ns, this, true); + content->RemoveEventListener(u"drag"_ns, this, true); + content->RemoveEventListener(u"dragenter"_ns, this, true); + content->RemoveEventListener(u"dragover"_ns, this, true); + content->RemoveEventListener(u"dragleave"_ns, this, true); + content->RemoveEventListener(u"dragexit"_ns, this, true); + content->RemoveEventListener(u"dragstart"_ns, this, true); + content->RemoveEventListener(u"dragend"_ns, this, true); + content->RemoveSystemEventListener(u"compositionstart"_ns, this, true); + content->RemoveSystemEventListener(u"compositionend"_ns, this, true); + content->RemoveSystemEventListener(u"text"_ns, this, true); if (mWidget) { if (mPluginWindow) { @@ -2731,38 +2727,33 @@ nsresult nsPluginInstanceOwner::Init(nsIContent* aContent) { // register context menu listener mCXMenuListener = new nsPluginDOMContextMenuListener(aContent); - aContent->AddEventListener(NS_LITERAL_STRING("focus"), this, false, false); - aContent->AddEventListener(NS_LITERAL_STRING("blur"), this, false, false); - aContent->AddEventListener(NS_LITERAL_STRING("mouseup"), this, false, false); - aContent->AddEventListener(NS_LITERAL_STRING("mousedown"), this, false, - false); - aContent->AddEventListener(NS_LITERAL_STRING("mousemove"), this, false, - false); - aContent->AddEventListener(NS_LITERAL_STRING("click"), this, false, false); - aContent->AddEventListener(NS_LITERAL_STRING("dblclick"), this, false, false); - aContent->AddEventListener(NS_LITERAL_STRING("mouseover"), this, false, - false); - aContent->AddEventListener(NS_LITERAL_STRING("mouseout"), this, false, false); + aContent->AddEventListener(u"focus"_ns, this, false, false); + aContent->AddEventListener(u"blur"_ns, this, false, false); + aContent->AddEventListener(u"mouseup"_ns, this, false, false); + aContent->AddEventListener(u"mousedown"_ns, this, false, false); + aContent->AddEventListener(u"mousemove"_ns, this, false, false); + aContent->AddEventListener(u"click"_ns, this, false, false); + aContent->AddEventListener(u"dblclick"_ns, this, false, false); + aContent->AddEventListener(u"mouseover"_ns, this, false, false); + aContent->AddEventListener(u"mouseout"_ns, this, false, false); // "keypress" event should be handled when it's in the default event group // if the event is fired in content. Otherwise, it should be handled when // it's in the system event group. - aContent->AddEventListener(NS_LITERAL_STRING("keypress"), this, true); - aContent->AddSystemEventListener(NS_LITERAL_STRING("keypress"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("keydown"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("keyup"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("drop"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("drag"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragenter"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragover"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragleave"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragexit"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragstart"), this, true); - aContent->AddEventListener(NS_LITERAL_STRING("dragend"), this, true); - aContent->AddSystemEventListener(NS_LITERAL_STRING("compositionstart"), this, - true); - aContent->AddSystemEventListener(NS_LITERAL_STRING("compositionend"), this, - true); - aContent->AddSystemEventListener(NS_LITERAL_STRING("text"), this, true); + aContent->AddEventListener(u"keypress"_ns, this, true); + aContent->AddSystemEventListener(u"keypress"_ns, this, true); + aContent->AddEventListener(u"keydown"_ns, this, true); + aContent->AddEventListener(u"keyup"_ns, this, true); + aContent->AddEventListener(u"drop"_ns, this, true); + aContent->AddEventListener(u"drag"_ns, this, true); + aContent->AddEventListener(u"dragenter"_ns, this, true); + aContent->AddEventListener(u"dragover"_ns, this, true); + aContent->AddEventListener(u"dragleave"_ns, this, true); + aContent->AddEventListener(u"dragexit"_ns, this, true); + aContent->AddEventListener(u"dragstart"_ns, this, true); + aContent->AddEventListener(u"dragend"_ns, this, true); + aContent->AddSystemEventListener(u"compositionstart"_ns, this, true); + aContent->AddSystemEventListener(u"compositionend"_ns, this, true); + aContent->AddSystemEventListener(u"text"_ns, this, true); return NS_OK; } @@ -3167,12 +3158,10 @@ void nsPluginInstanceOwner::SetFrame(nsPluginFrame* aFrame) { nsCOMPtr windowRoot = content->OwnerDoc()->GetWindow()->GetTopWindowRoot(); if (windowRoot) { - windowRoot->RemoveEventListener(NS_LITERAL_STRING("activate"), this, + windowRoot->RemoveEventListener(u"activate"_ns, this, false); + windowRoot->RemoveEventListener(u"deactivate"_ns, this, false); + windowRoot->RemoveEventListener(u"MozPerformDelayedBlur"_ns, this, false); - windowRoot->RemoveEventListener(NS_LITERAL_STRING("deactivate"), this, - false); - windowRoot->RemoveEventListener( - NS_LITERAL_STRING("MozPerformDelayedBlur"), this, false); } } @@ -3207,12 +3196,10 @@ void nsPluginInstanceOwner::SetFrame(nsPluginFrame* aFrame) { nsCOMPtr windowRoot = content->OwnerDoc()->GetWindow()->GetTopWindowRoot(); if (windowRoot) { - windowRoot->AddEventListener(NS_LITERAL_STRING("activate"), this, false, + windowRoot->AddEventListener(u"activate"_ns, this, false, false); + windowRoot->AddEventListener(u"deactivate"_ns, this, false, false); + windowRoot->AddEventListener(u"MozPerformDelayedBlur"_ns, this, false, false); - windowRoot->AddEventListener(NS_LITERAL_STRING("deactivate"), this, - false, false); - windowRoot->AddEventListener(NS_LITERAL_STRING("MozPerformDelayedBlur"), - this, false, false); } } } @@ -3279,7 +3266,7 @@ void nsPluginInstanceOwner::GeneratePluginEvent( nsPluginDOMContextMenuListener::nsPluginDOMContextMenuListener( nsIContent* aContent) { - aContent->AddEventListener(NS_LITERAL_STRING("contextmenu"), this, true); + aContent->AddEventListener(u"contextmenu"_ns, this, true); } nsPluginDOMContextMenuListener::~nsPluginDOMContextMenuListener() = default; @@ -3295,5 +3282,5 @@ nsPluginDOMContextMenuListener::HandleEvent(Event* aEvent) { void nsPluginDOMContextMenuListener::Destroy(nsIContent* aContent) { // Unregister context menu listener - aContent->RemoveEventListener(NS_LITERAL_STRING("contextmenu"), this, true); + aContent->RemoveEventListener(u"contextmenu"_ns, this, true); } diff --git a/dom/plugins/base/nsPluginStreamListenerPeer.cpp b/dom/plugins/base/nsPluginStreamListenerPeer.cpp index 8b3dec50684a..1edfd24b48d3 100644 --- a/dom/plugins/base/nsPluginStreamListenerPeer.cpp +++ b/dom/plugins/base/nsPluginStreamListenerPeer.cpp @@ -436,8 +436,8 @@ nsresult nsPluginStreamListenerPeer::SetUpStreamListener(nsIRequest* request, // we require a content len // get Last-Modified header for plugin info nsAutoCString lastModified; - if (NS_SUCCEEDED(httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("last-modified"), lastModified)) && + if (NS_SUCCEEDED( + httpChannel->GetResponseHeader("last-modified"_ns, lastModified)) && !lastModified.IsEmpty()) { PRTime time64; PR_ParseTimeString(lastModified.get(), true, diff --git a/dom/plugins/base/nsPluginsDirDarwin.cpp b/dom/plugins/base/nsPluginsDirDarwin.cpp index d6b62348a809..9c5f3c674ab4 100644 --- a/dom/plugins/base/nsPluginsDirDarwin.cpp +++ b/dom/plugins/base/nsPluginsDirDarwin.cpp @@ -414,7 +414,7 @@ nsresult nsPluginFile::GetPluginInfo(nsPluginInfo& info, // See bug 1086977. if (nsCocoaFeatures::OnYosemiteOrLater()) { if (fileName.EqualsLiteral("fbplugin") || - StringBeginsWith(fileName, NS_LITERAL_CSTRING("fbplugin_"))) { + StringBeginsWith(fileName, "fbplugin_"_ns)) { nsAutoCString msg; msg.AppendPrintf("Preventing load of %s (see bug 1086977)", fileName.get()); diff --git a/dom/plugins/base/nsPluginsDirWin.cpp b/dom/plugins/base/nsPluginsDirWin.cpp index c8508924b34f..04e20f46d0d5 100644 --- a/dom/plugins/base/nsPluginsDirWin.cpp +++ b/dom/plugins/base/nsPluginsDirWin.cpp @@ -199,11 +199,11 @@ bool nsPluginsDir::IsPluginFile(nsIFile* file) { } ToLowerCase(filename); - if (StringBeginsWith(filename, NS_LITERAL_STRING("np")) && - StringEndsWith(filename, NS_LITERAL_STRING(".dll"))) { + if (StringBeginsWith(filename, u"np"_ns) && + StringEndsWith(filename, u".dll"_ns)) { // don't load OJI-based Java plugins - if (StringBeginsWith(filename, NS_LITERAL_STRING("npoji")) || - StringBeginsWith(filename, NS_LITERAL_STRING("npjava"))) + if (StringBeginsWith(filename, u"npoji"_ns) || + StringBeginsWith(filename, u"npjava"_ns)) return false; return true; } diff --git a/dom/plugins/ipc/PluginHangUIParent.cpp b/dom/plugins/ipc/PluginHangUIParent.cpp index 76cc223cff08..e39bf45380e0 100644 --- a/dom/plugins/ipc/PluginHangUIParent.cpp +++ b/dom/plugins/ipc/PluginHangUIParent.cpp @@ -316,9 +316,9 @@ bool PluginHangUIParent::RecvUserResponse(const unsigned int& aResponse) { int responseCode; if (aResponse & HANGUI_USER_RESPONSE_STOP) { // User clicked Stop - mModule->TerminateChildProcess( - mMainThreadMessageLoop, mozilla::ipc::kInvalidProcessId, - NS_LITERAL_CSTRING("ModalHangUI"), EmptyString()); + mModule->TerminateChildProcess(mMainThreadMessageLoop, + mozilla::ipc::kInvalidProcessId, + "ModalHangUI"_ns, EmptyString()); responseCode = 1; } else if (aResponse & HANGUI_USER_RESPONSE_CONTINUE) { mModule->OnHangUIContinue(); diff --git a/dom/plugins/ipc/PluginModuleParent.cpp b/dom/plugins/ipc/PluginModuleParent.cpp index fff6cfc2360c..fdb5392bbee6 100644 --- a/dom/plugins/ipc/PluginModuleParent.cpp +++ b/dom/plugins/ipc/PluginModuleParent.cpp @@ -939,17 +939,16 @@ void PluginModuleChromeParent::AnnotateHang( be pretty obvious from the hang stack that we're in a plugin call when the hang occurred. */ if (flags & kHangUIShown) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("HangUIShown"), true); + aAnnotations.AddAnnotation(u"HangUIShown"_ns, true); } if (flags & kHangUIContinued) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("HangUIContinued"), true); + aAnnotations.AddAnnotation(u"HangUIContinued"_ns, true); } if (flags & kHangUIDontShow) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("HangUIDontShow"), true); + aAnnotations.AddAnnotation(u"HangUIDontShow"_ns, true); } - aAnnotations.AddAnnotation(NS_LITERAL_STRING("pluginName"), mPluginName); - aAnnotations.AddAnnotation(NS_LITERAL_STRING("pluginVersion"), - mPluginVersion); + aAnnotations.AddAnnotation(u"pluginName"_ns, mPluginName); + aAnnotations.AddAnnotation(u"pluginVersion"_ns, mPluginVersion); } } @@ -980,7 +979,7 @@ bool PluginModuleChromeParent::ShouldContinueFromReplyTimeout() { #endif // XP_WIN TerminateChildProcess(MessageLoop::current(), mozilla::ipc::kInvalidProcessId, - NS_LITERAL_CSTRING("ModalHangUI"), EmptyString()); + "ModalHangUI"_ns, EmptyString()); GetIPCChannel()->CloseWithTimeout(); return false; } @@ -1019,7 +1018,7 @@ void PluginModuleChromeParent::TakeFullMinidump(base::ProcessId aContentPid, // We have a single browser report, generate a new plugin process parent // report and pair it up with the browser report handed in. reportsReady = mCrashReporter->GenerateMinidumpAndPair( - this, browserDumpFile, NS_LITERAL_CSTRING("browser")); + this, browserDumpFile, "browser"_ns); if (!reportsReady) { browserDumpFile = nullptr; @@ -1035,7 +1034,7 @@ void PluginModuleChromeParent::TakeFullMinidump(base::ProcessId aContentPid, reportsReady = mCrashReporter->GenerateMinidumpAndPair( this, nullptr, // Pair with a dump of this process and thread. - NS_LITERAL_CSTRING("browser")); + "browser"_ns); } if (reportsReady) { @@ -1049,18 +1048,18 @@ void PluginModuleChromeParent::TakeFullMinidump(base::ProcessId aContentPid, // If we have handles to the flash sandbox processes on Windows, // include those minidumps as well. if (CreatePluginMinidump(mFlashProcess1, 0, pluginDumpFile, - NS_LITERAL_CSTRING("flash1"))) { + "flash1"_ns)) { additionalDumps.AppendLiteral(",flash1"); } if (CreatePluginMinidump(mFlashProcess2, 0, pluginDumpFile, - NS_LITERAL_CSTRING("flash2"))) { + "flash2"_ns)) { additionalDumps.AppendLiteral(",flash2"); } #endif // MOZ_CRASHREPORTER_INJECTOR if (aContentPid != mozilla::ipc::kInvalidProcessId) { // Include the content process minidump if (CreatePluginMinidump(aContentPid, 0, pluginDumpFile, - NS_LITERAL_CSTRING("content"))) { + "content"_ns)) { additionalDumps.AppendLiteral(",content"); } } @@ -1392,8 +1391,7 @@ nsresult PluginModuleParent::GetRunID(uint32_t* aRunID) { void PluginModuleChromeParent::ActorDestroy(ActorDestroyReason why) { if (why == AbnormalShutdown) { ProcessFirstMinidump(); - Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, - NS_LITERAL_CSTRING("plugin"), 1); + Telemetry::Accumulate(Telemetry::SUBPROCESS_ABNORMAL_ABORT, "plugin"_ns, 1); } // We can't broadcast settings changes anymore. @@ -2488,7 +2486,7 @@ void PluginModuleChromeParent::InitializeInjector() { if (kNotFound == lastSlash) return; if (!StringBeginsWith(Substring(path, lastSlash + 1), - NS_LITERAL_CSTRING(FLASH_PLUGIN_PREFIX))) + nsLiteralCString(FLASH_PLUGIN_PREFIX))) return; mFinishInitTask = mChromeTaskFactory.NewTask(); diff --git a/dom/power/WakeLock.cpp b/dom/power/WakeLock.cpp index e2e4cc3324d8..4243164fea1d 100644 --- a/dom/power/WakeLock.cpp +++ b/dom/power/WakeLock.cpp @@ -111,8 +111,7 @@ WakeLock::Observe(nsISupports* aSubject, const char* aTopic, } uint64_t childID = 0; - nsresult rv = - props->GetPropertyAsUint64(NS_LITERAL_STRING("childID"), &childID); + nsresult rv = props->GetPropertyAsUint64(u"childID"_ns, &childID); if (NS_SUCCEEDED(rv)) { if (childID == mContentParentID) { mLocked = false; @@ -151,15 +150,15 @@ void WakeLock::AttachEventListener() { if (nsCOMPtr window = do_QueryReferent(mWindow)) { nsCOMPtr doc = window->GetExtantDoc(); if (doc) { - doc->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"), this, + doc->AddSystemEventListener(u"visibilitychange"_ns, this, /* useCapture = */ true, /* wantsUntrusted = */ false); nsCOMPtr target = do_QueryInterface(window); - target->AddSystemEventListener(NS_LITERAL_STRING("pagehide"), this, + target->AddSystemEventListener(u"pagehide"_ns, this, /* useCapture = */ true, /* wantsUntrusted = */ false); - target->AddSystemEventListener(NS_LITERAL_STRING("pageshow"), this, + target->AddSystemEventListener(u"pageshow"_ns, this, /* useCapture = */ true, /* wantsUntrusted = */ false); } @@ -170,13 +169,12 @@ void WakeLock::DetachEventListener() { if (nsCOMPtr window = do_QueryReferent(mWindow)) { nsCOMPtr doc = window->GetExtantDoc(); if (doc) { - doc->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"), - this, + doc->RemoveSystemEventListener(u"visibilitychange"_ns, this, /* useCapture = */ true); nsCOMPtr target = do_QueryInterface(window); - target->RemoveSystemEventListener(NS_LITERAL_STRING("pagehide"), this, + target->RemoveSystemEventListener(u"pagehide"_ns, this, /* useCapture = */ true); - target->RemoveSystemEventListener(NS_LITERAL_STRING("pageshow"), this, + target->RemoveSystemEventListener(u"pageshow"_ns, this, /* useCapture = */ true); } } diff --git a/dom/presentation/PresentationAvailability.cpp b/dom/presentation/PresentationAvailability.cpp index c8fbcde2464b..93e48a6ef66d 100644 --- a/dom/presentation/PresentationAvailability.cpp +++ b/dom/presentation/PresentationAvailability.cpp @@ -193,7 +193,6 @@ void PresentationAvailability::UpdateAvailabilityAndDispatchEvent( } if (isChanged) { - Unused << NS_WARN_IF( - NS_FAILED(DispatchTrustedEvent(NS_LITERAL_STRING("change")))); + Unused << NS_WARN_IF(NS_FAILED(DispatchTrustedEvent(u"change"_ns))); } } diff --git a/dom/presentation/PresentationConnection.cpp b/dom/presentation/PresentationConnection.cpp index cdc3599994a3..567f43a74703 100644 --- a/dom/presentation/PresentationConnection.cpp +++ b/dom/presentation/PresentationConnection.cpp @@ -200,7 +200,7 @@ void PresentationConnection::Send(const nsAString& aData, ErrorResult& aRv) { do_GetService(PRESENTATION_SERVICE_CONTRACTID); if (NS_WARN_IF(!service)) { AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send message due to an internal error.")); + u"Unable to send message due to an internal error."_ns); return; } @@ -209,9 +209,8 @@ void PresentationConnection::Send(const nsAString& aData, ErrorResult& aRv) { const uint32_t kMaxMessageLength = 256; nsAutoString data(Substring(aData, 0, kMaxMessageLength)); - AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send message: \"") + data + - NS_LITERAL_STRING("\"")); + AsyncCloseConnectionWithErrorMsg(u"Unable to send message: \""_ns + data + + u"\""_ns); } } @@ -229,14 +228,14 @@ void PresentationConnection::Send(Blob& aData, ErrorResult& aRv) { do_GetService(PRESENTATION_SERVICE_CONTRACTID); if (NS_WARN_IF(!service)) { AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send message due to an internal error.")); + u"Unable to send message due to an internal error."_ns); return; } nsresult rv = service->SendSessionBlob(mId, mRole, &aData); if (NS_WARN_IF(NS_FAILED(rv))) { AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send binary message for Blob message.")); + u"Unable to send binary message for Blob message."_ns); } } @@ -254,7 +253,7 @@ void PresentationConnection::Send(const ArrayBuffer& aData, ErrorResult& aRv) { do_GetService(PRESENTATION_SERVICE_CONTRACTID); if (NS_WARN_IF(!service)) { AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send message due to an internal error.")); + u"Unable to send message due to an internal error."_ns); return; } @@ -268,8 +267,8 @@ void PresentationConnection::Send(const ArrayBuffer& aData, ErrorResult& aRv) { nsresult rv = service->SendSessionBinaryMsg(mId, mRole, msgString); if (NS_WARN_IF(NS_FAILED(rv))) { - AsyncCloseConnectionWithErrorMsg(NS_LITERAL_STRING( - "Unable to send binary message for ArrayBuffer message.")); + AsyncCloseConnectionWithErrorMsg(nsLiteralString( + u"Unable to send binary message for ArrayBuffer message.")); } } @@ -288,7 +287,7 @@ void PresentationConnection::Send(const ArrayBufferView& aData, do_GetService(PRESENTATION_SERVICE_CONTRACTID); if (NS_WARN_IF(!service)) { AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to send message due to an internal error.")); + u"Unable to send message due to an internal error."_ns); return; } @@ -302,8 +301,8 @@ void PresentationConnection::Send(const ArrayBufferView& aData, nsresult rv = service->SendSessionBinaryMsg(mId, mRole, msgString); if (NS_WARN_IF(NS_FAILED(rv))) { - AsyncCloseConnectionWithErrorMsg(NS_LITERAL_STRING( - "Unable to send binary message for ArrayBufferView message.")); + AsyncCloseConnectionWithErrorMsg(nsLiteralString( + u"Unable to send binary message for ArrayBufferView message.")); } } @@ -415,8 +414,8 @@ nsresult PresentationConnection::ProcessStateChanged(nsresult aReason) { return NS_OK; } - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("connect"), CanBubble::eNo); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"connect"_ns, CanBubble::eNo); return asyncDispatcher->PostDOMEvent(); } case PresentationConnectionState::Closed: { @@ -445,8 +444,8 @@ nsresult PresentationConnection::ProcessStateChanged(nsresult aReason) { case PresentationConnectionState::Terminated: { if (!nsContentUtils::ShouldResistFingerprinting()) { // Ensure onterminate event is fired. - RefPtr asyncDispatcher = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("terminate"), CanBubble::eNo); + RefPtr asyncDispatcher = + new AsyncEventDispatcher(this, u"terminate"_ns, CanBubble::eNo); Unused << NS_WARN_IF(NS_FAILED(asyncDispatcher->PostDOMEvent())); } @@ -486,8 +485,7 @@ PresentationConnection::NotifyMessage(const nsAString& aSessionId, } if (NS_WARN_IF(NS_FAILED(DoReceiveMessage(aData, aIsBinary)))) { - AsyncCloseConnectionWithErrorMsg( - NS_LITERAL_STRING("Unable to receive a message.")); + AsyncCloseConnectionWithErrorMsg(u"Unable to receive a message."_ns); return NS_ERROR_FAILURE; } @@ -557,8 +555,7 @@ nsresult PresentationConnection::DispatchConnectionCloseEvent( init.mMessage = aMessage; RefPtr closedEvent = - PresentationConnectionCloseEvent::Constructor( - this, NS_LITERAL_STRING("close"), init); + PresentationConnectionCloseEvent::Constructor(this, u"close"_ns, init); closedEvent->SetTrusted(true); if (aDispatchNow) { @@ -588,10 +585,9 @@ nsresult PresentationConnection::DispatchMessageEvent( RefPtr messageEvent = new MessageEvent(this, nullptr, nullptr); - messageEvent->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), - CanBubble::eNo, Cancelable::eNo, aData, origin, - EmptyString(), nullptr, - Sequence>()); + messageEvent->InitMessageEvent( + nullptr, u"message"_ns, CanBubble::eNo, Cancelable::eNo, aData, origin, + EmptyString(), nullptr, Sequence>()); messageEvent->SetTrusted(true); RefPtr asyncDispatcher = diff --git a/dom/presentation/PresentationConnectionList.cpp b/dom/presentation/PresentationConnectionList.cpp index 8f0c4e6d1957..7b2cc0b5a164 100644 --- a/dom/presentation/PresentationConnectionList.cpp +++ b/dom/presentation/PresentationConnectionList.cpp @@ -60,7 +60,7 @@ nsresult PresentationConnectionList::DispatchConnectionAvailableEvent( RefPtr event = PresentationConnectionAvailableEvent::Constructor( - this, NS_LITERAL_STRING("connectionavailable"), init); + this, u"connectionavailable"_ns, init); if (NS_WARN_IF(!event)) { return NS_ERROR_FAILURE; diff --git a/dom/presentation/PresentationRequest.cpp b/dom/presentation/PresentationRequest.cpp index 020cbda1c1b1..690f286273fa 100644 --- a/dom/presentation/PresentationRequest.cpp +++ b/dom/presentation/PresentationRequest.cpp @@ -427,7 +427,7 @@ nsresult PresentationRequest::DispatchConnectionAvailableEvent( RefPtr event = PresentationConnectionAvailableEvent::Constructor( - this, NS_LITERAL_STRING("connectionavailable"), init); + this, u"connectionavailable"_ns, init); if (NS_WARN_IF(!event)) { return NS_ERROR_FAILURE; } diff --git a/dom/presentation/provider/MulticastDNSDeviceProvider.cpp b/dom/presentation/provider/MulticastDNSDeviceProvider.cpp index c8ea5e8b44fd..8f9c11e119a9 100644 --- a/dom/presentation/provider/MulticastDNSDeviceProvider.cpp +++ b/dom/presentation/provider/MulticastDNSDeviceProvider.cpp @@ -64,8 +64,8 @@ static void GetAndroidDeviceName(nsACString& aRetVal) { do_GetService("@mozilla.org/system-info;1"); MOZ_ASSERT(infoService, "Could not find a system info service"); - Unused << NS_WARN_IF(NS_FAILED(infoService->GetPropertyAsACString( - NS_LITERAL_STRING("device"), aRetVal))); + Unused << NS_WARN_IF( + NS_FAILED(infoService->GetPropertyAsACString(u"device"_ns, aRetVal))); } #endif // MOZ_WIDGET_ANDROID @@ -291,8 +291,8 @@ nsresult MulticastDNSDeviceProvider::RegisterMDNSService() { if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - if (NS_WARN_IF(NS_FAILED(rv = serviceInfo->SetServiceType( - NS_LITERAL_CSTRING(SERVICE_TYPE))))) { + if (NS_WARN_IF(NS_FAILED( + rv = serviceInfo->SetServiceType(nsLiteralCString(SERVICE_TYPE))))) { return rv; } if (NS_WARN_IF(NS_FAILED(rv = serviceInfo->SetServiceName(mServiceName)))) { @@ -602,10 +602,9 @@ MulticastDNSDeviceProvider::ForceDiscovery() { StopDiscovery(NS_OK); - if (NS_WARN_IF( - NS_FAILED(rv = mMulticastDNS->StartDiscovery( - NS_LITERAL_CSTRING(SERVICE_TYPE), mWrappedListener, - getter_AddRefs(mDiscoveryRequest))))) { + if (NS_WARN_IF(NS_FAILED(rv = mMulticastDNS->StartDiscovery( + nsLiteralCString(SERVICE_TYPE), mWrappedListener, + getter_AddRefs(mDiscoveryRequest))))) { return rv; } diff --git a/dom/prio/test/gtest/TestPrioEncoder.cpp b/dom/prio/test/gtest/TestPrioEncoder.cpp index 3e728efa922c..321d7e2a0d89 100644 --- a/dom/prio/test/gtest/TestPrioEncoder.cpp +++ b/dom/prio/test/gtest/TestPrioEncoder.cpp @@ -30,7 +30,7 @@ TEST(PrioEncoder, BooleanLimitExceeded) mozilla::dom::GlobalObject global(cx, xpc::PrivilegedJunkScope()); - nsCString batchID = NS_LITERAL_CSTRING("abc123"); + nsCString batchID = "abc123"_ns; mozilla::dom::PrioParams prioParams; FallibleTArray sequence; diff --git a/dom/promise/PromiseDebugging.cpp b/dom/promise/PromiseDebugging.cpp index 8c129a38744a..d0ec210736ef 100644 --- a/dom/promise/PromiseDebugging.cpp +++ b/dom/promise/PromiseDebugging.cpp @@ -167,7 +167,7 @@ void PromiseDebugging::Init() { FlushRejections::Init(); // Generate a prefix for identifiers: "PromiseDebugging.$processid." - sIDPrefix = NS_LITERAL_STRING("PromiseDebugging."); + sIDPrefix = u"PromiseDebugging."_ns; if (XRE_IsContentProcess()) { sIDPrefix.AppendInt(ContentChild::GetSingleton()->GetID()); sIDPrefix.Append('.'); diff --git a/dom/prototype/PrototypeDocumentContentSink.cpp b/dom/prototype/PrototypeDocumentContentSink.cpp index 596d3a66e885..292e288a7bf2 100644 --- a/dom/prototype/PrototypeDocumentContentSink.cpp +++ b/dom/prototype/PrototypeDocumentContentSink.cpp @@ -405,9 +405,9 @@ nsresult PrototypeDocumentContentSink::ResumeWalk() { nsresult rv = ResumeWalkInternal(); if (NS_FAILED(rv)) { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING("Failed to load document from prototype document."), - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Prototype Document"), - mDocument, mDocumentURI); + u"Failed to load document from prototype document."_ns, + nsIScriptError::errorFlag, "Prototype Document"_ns, mDocument, + mDocumentURI); } return rv; } @@ -551,10 +551,10 @@ nsresult PrototypeDocumentContentSink::ResumeWalkInternal() { if (piProto->mTarget.EqualsLiteral("xml-stylesheet")) { AutoTArray params = {piProto->mTarget}; - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("XUL Document"), - nullptr, nsContentUtils::eXUL_PROPERTIES, "PINotInProlog", - params, docURI); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, + "XUL Document"_ns, nullptr, + nsContentUtils::eXUL_PROPERTIES, + "PINotInProlog", params, docURI); } nsIContent* parent = element.get(); @@ -608,10 +608,9 @@ nsresult PrototypeDocumentContentSink::DoneWalking() { mDocument->SetReadyStateInternal(Document::READYSTATE_INTERACTIVE); mDocument->NotifyPossibleTitleChange(false); - nsContentUtils::DispatchEventOnlyToChrome( - mDocument, ToSupports(mDocument), - NS_LITERAL_STRING("MozBeforeInitialXULLayout"), CanBubble::eYes, - Cancelable::eNo); + nsContentUtils::DispatchEventOnlyToChrome(mDocument, ToSupports(mDocument), + u"MozBeforeInitialXULLayout"_ns, + CanBubble::eYes, Cancelable::eNo); } if (mScriptLoader) { diff --git a/dom/push/PushManager.cpp b/dom/push/PushManager.cpp index 9fba17cf0559..c38921012b8b 100644 --- a/dom/push/PushManager.cpp +++ b/dom/push/PushManager.cpp @@ -44,7 +44,7 @@ nsresult GetPermissionState(nsIPrincipal* aPrincipal, } uint32_t permission = nsIPermissionManager::UNKNOWN_ACTION; nsresult rv = permManager->TestExactPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("desktop-notification"), &permission); + aPrincipal, "desktop-notification"_ns, &permission); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -75,15 +75,15 @@ nsresult GetSubscriptionParams(nsIPushSubscription* aSubscription, return rv; } - rv = aSubscription->GetKey(NS_LITERAL_STRING("p256dh"), aRawP256dhKey); + rv = aSubscription->GetKey(u"p256dh"_ns, aRawP256dhKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aSubscription->GetKey(NS_LITERAL_STRING("auth"), aAuthSecret); + rv = aSubscription->GetKey(u"auth"_ns, aAuthSecret); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aSubscription->GetKey(NS_LITERAL_STRING("appServer"), aAppServerKey); + rv = aSubscription->GetKey(u"appServer"_ns, aAppServerKey); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/push/PushNotifier.cpp b/dom/push/PushNotifier.cpp index 7b410e9f7c6a..59940ff53c74 100644 --- a/dom/push/PushNotifier.cpp +++ b/dom/push/PushNotifier.cpp @@ -433,11 +433,11 @@ nsresult PushErrorDispatcher::NotifyWorkers() { (!mPrincipal || mPrincipal->IsSystemPrincipal())) { // For system subscriptions, log the error directly to the browser console. return nsContentUtils::ReportToConsoleNonLocalized( - mMessage, mFlags, NS_LITERAL_CSTRING("Push"), nullptr, /* aDocument */ - nullptr, /* aURI */ - EmptyString(), /* aLine */ - 0, /* aLineNumber */ - 0, /* aColumnNumber */ + mMessage, mFlags, "Push"_ns, nullptr, /* aDocument */ + nullptr, /* aURI */ + EmptyString(), /* aLine */ + 0, /* aLineNumber */ + 0, /* aColumnNumber */ nsContentUtils::eOMIT_LOCATION); } @@ -472,11 +472,11 @@ nsresult PushErrorDispatcher::HandleNoChildProcesses() { return rv; } return nsContentUtils::ReportToConsoleNonLocalized( - mMessage, mFlags, NS_LITERAL_CSTRING("Push"), nullptr, /* aDocument */ - scopeURI, /* aURI */ - EmptyString(), /* aLine */ - 0, /* aLineNumber */ - 0, /* aColumnNumber */ + mMessage, mFlags, "Push"_ns, nullptr, /* aDocument */ + scopeURI, /* aURI */ + EmptyString(), /* aLine */ + 0, /* aLineNumber */ + 0, /* aColumnNumber */ nsContentUtils::eOMIT_LOCATION); } diff --git a/dom/quota/ActorsParent.cpp b/dom/quota/ActorsParent.cpp index 16ec407a54e1..0370b1cbd692 100644 --- a/dom/quota/ActorsParent.cpp +++ b/dom/quota/ActorsParent.cpp @@ -240,9 +240,9 @@ nsresult CreateTables(mozIStorageConnection* aConnection) { // Table `database` nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE database" - "( cache_version INTEGER NOT NULL DEFAULT 0" - ");")); + nsLiteralCString("CREATE TABLE database" + "( cache_version INTEGER NOT NULL DEFAULT 0" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -274,8 +274,7 @@ nsresult LoadCacheVersion(mozIStorageConnection* aConnection, nsCOMPtr stmt; nsresult rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("SELECT cache_version FROM database"), - getter_AddRefs(stmt)); + "SELECT cache_version FROM database"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -307,13 +306,12 @@ nsresult SaveCacheVersion(mozIStorageConnection* aConnection, nsCOMPtr stmt; nsresult rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("UPDATE database SET cache_version = :version;"), - getter_AddRefs(stmt)); + "UPDATE database SET cache_version = :version;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("version"), aVersion); + rv = stmt->BindInt32ByName("version"_ns, aVersion); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -332,39 +330,39 @@ nsresult CreateCacheTables(mozIStorageConnection* aConnection) { // Table `cache` nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE cache" - "( valid INTEGER NOT NULL DEFAULT 0" - ", build_id TEXT NOT NULL DEFAULT ''" - ");")); + nsLiteralCString("CREATE TABLE cache" + "( valid INTEGER NOT NULL DEFAULT 0" + ", build_id TEXT NOT NULL DEFAULT ''" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `repository` - rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE repository" - "( id INTEGER PRIMARY KEY" - ", name TEXT NOT NULL" - ");")); + rv = + aConnection->ExecuteSimpleSQL(nsLiteralCString("CREATE TABLE repository" + "( id INTEGER PRIMARY KEY" + ", name TEXT NOT NULL" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } // Table `origin` rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE origin" - "( repository_id INTEGER NOT NULL" - ", origin TEXT NOT NULL" - ", group_ TEXT NOT NULL" - ", client_usages TEXT NOT NULL" - ", usage INTEGER NOT NULL" - ", last_access_time INTEGER NOT NULL" - ", accessed INTEGER NOT NULL" - ", persisted INTEGER NOT NULL" - ", PRIMARY KEY (repository_id, origin)" - ", FOREIGN KEY (repository_id) " - "REFERENCES repository(id) " - ");")); + nsLiteralCString("CREATE TABLE origin" + "( repository_id INTEGER NOT NULL" + ", origin TEXT NOT NULL" + ", group_ TEXT NOT NULL" + ", client_usages TEXT NOT NULL" + ", usage INTEGER NOT NULL" + ", last_access_time INTEGER NOT NULL" + ", accessed INTEGER NOT NULL" + ", persisted INTEGER NOT NULL" + ", PRIMARY KEY (repository_id, origin)" + ", FOREIGN KEY (repository_id) " + "REFERENCES repository(id) " + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -424,14 +422,12 @@ nsresult InvalidateCache(mozIStorageConnection* aConnection) { mozStorageTransaction transaction( aConnection, false, mozIStorageConnection::TRANSACTION_IMMEDIATE); - nsresult rv = - aConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM origin;")); + nsresult rv = aConnection->ExecuteSimpleSQL("DELETE FROM origin;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE cache SET valid = 0")); + rv = aConnection->ExecuteSimpleSQL("UPDATE cache SET valid = 0"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -551,7 +547,7 @@ nsresult InitializeLocalStorageArchive(mozIStorageConnection* aConnection, AssertIsOnIOThread(); MOZ_ASSERT(aConnection); - nsresult rv = aConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = aConnection->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE database(version INTEGER NOT NULL DEFAULT 0);")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -559,13 +555,13 @@ nsresult InitializeLocalStorageArchive(mozIStorageConnection* aConnection, nsCOMPtr stmt; rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO database (version) VALUES (:version)"), + "INSERT INTO database (version) VALUES (:version)"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("version"), aVersion); + rv = stmt->BindInt32ByName("version"_ns, aVersion); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -584,8 +580,7 @@ nsresult IsLocalStorageArchiveInitialized(mozIStorageConnection* aConnection, MOZ_ASSERT(aConnection); bool exists; - nsresult rv = - aConnection->TableExists(NS_LITERAL_CSTRING("database"), &exists); + nsresult rv = aConnection->TableExists("database"_ns, &exists); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -600,8 +595,8 @@ nsresult LoadLocalStorageArchiveVersion(mozIStorageConnection* aConnection, MOZ_ASSERT(aConnection); nsCOMPtr stmt; - nsresult rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("SELECT version FROM database"), getter_AddRefs(stmt)); + nsresult rv = aConnection->CreateStatement("SELECT version FROM database"_ns, + getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -634,13 +629,13 @@ nsresult SaveLocalStorageArchiveVersion(mozIStorageConnection* aConnection, nsCOMPtr stmt; nsresult rv = aConnection->CreateStatement( - NS_LITERAL_CSTRING("UPDATE database SET version = :version;"), + "UPDATE database SET version = :version;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("version"), aVersion); + rv = stmt->BindInt32ByName("version"_ns, aVersion); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -4334,7 +4329,7 @@ nsresult QuotaManager::LoadQuota() { auto LoadQuotaFromCache = [&]() { nsCOMPtr stmt; nsresult rv = mStorageConnection->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT repository_id, origin, group_, client_usages, usage, " "last_access_time, accessed, persisted " "FROM origin"), @@ -4502,8 +4497,8 @@ nsresult QuotaManager::LoadQuota() { if (mCacheUsable) { nsCOMPtr stmt; rv = mStorageConnection->CreateStatement( - NS_LITERAL_CSTRING("SELECT valid, build_id " - "FROM cache"), + nsLiteralCString("SELECT valid, build_id " + "FROM cache"), getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -4607,8 +4602,7 @@ void QuotaManager::UnloadQuota() { mozStorageTransaction transaction( mStorageConnection, false, mozIStorageConnection::TRANSACTION_IMMEDIATE); - nsresult rv = mStorageConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM origin;")); + nsresult rv = mStorageConnection->ExecuteSimpleSQL("DELETE FROM origin;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -4641,7 +4635,7 @@ void QuotaManager::UnloadQuota() { MOZ_ALWAYS_SUCCEEDS(insertStmt->Reset()); } else { rv = mStorageConnection->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT INTO origin (repository_id, origin, group_, " "client_usages, usage, last_access_time, accessed, " "persisted) " @@ -4674,19 +4668,18 @@ void QuotaManager::UnloadQuota() { nsCOMPtr stmt; rv = mStorageConnection->CreateStatement( - NS_LITERAL_CSTRING( - "UPDATE cache SET valid = :valid, build_id = :buildId;"), + "UPDATE cache SET valid = :valid, build_id = :buildId;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return; } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("valid"), 1); + rv = stmt->BindInt32ByName("valid"_ns, 1); if (NS_WARN_IF(NS_FAILED(rv))) { return; } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("buildId"), *gBuildId); + rv = stmt->BindUTF8StringByName("buildId"_ns, *gBuildId); if (NS_WARN_IF(NS_FAILED(rv))) { return; } @@ -5702,16 +5695,16 @@ nsresult QuotaManager::UpgradeStorageFrom2_2To2_3( // Table `database` nsresult rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE database" - "( cache_version INTEGER NOT NULL DEFAULT 0" - ");")); + nsLiteralCString("CREATE TABLE database" + "( cache_version INTEGER NOT NULL DEFAULT 0" + ");")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = aConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO database (cache_version) " - "VALUES (0)")); + nsLiteralCString("INSERT INTO database (cache_version) " + "VALUES (0)")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -5974,7 +5967,7 @@ nsresult QuotaManager::CreateLocalStorageArchiveConnectionFromWebAppsStore( if (connection) { // Find out the journal mode. nsCOMPtr stmt; - rv = connection->CreateStatement(NS_LITERAL_CSTRING("PRAGMA journal_mode;"), + rv = connection->CreateStatement("PRAGMA journal_mode;"_ns, getter_AddRefs(stmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -6002,8 +5995,7 @@ nsresult QuotaManager::CreateLocalStorageArchiveConnectionFromWebAppsStore( if (journalMode.EqualsLiteral("wal")) { // We don't copy the WAL file, so make sure the old database is fully // checkpointed. - rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA wal_checkpoint(TRUNCATE);")); + rv = connection->ExecuteSimpleSQL("PRAGMA wal_checkpoint(TRUNCATE);"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -6053,7 +6045,7 @@ nsresult QuotaManager::CreateLocalStorageArchiveConnectionFromWebAppsStore( // rollback journal also provides atomicity across multiple attached // databases which is import for the lazy data migration to work safely. rv = lsArchiveTmpConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA journal_mode = DELETE;")); + "PRAGMA journal_mode = DELETE;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -6445,8 +6437,7 @@ nsresult QuotaManager::EnsureStorageIsInitialized() { } // We want extra durability for this important file. - rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA synchronous = EXTRA;")); + rv = connection->ExecuteSimpleSQL("PRAGMA synchronous = EXTRA;"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -6518,8 +6509,8 @@ nsresult QuotaManager::EnsureStorageIsInitialized() { MOZ_ASSERT(storageVersion == kStorageVersion); rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO database (cache_version) " - "VALUES (0)")); + nsLiteralCString("INSERT INTO database (cache_version) " + "VALUES (0)")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -6686,8 +6677,8 @@ nsresult QuotaManager::EnsureStorageIsInitialized() { MOZ_ASSERT(cacheVersion == kCacheVersion); rv = connection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO cache (valid, build_id) " - "VALUES (0, '')")); + nsLiteralCString("INSERT INTO cache (valid, build_id) " + "VALUES (0, '')")); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -6699,23 +6690,21 @@ nsresult QuotaManager::EnsureStorageIsInitialized() { MOZ_ALWAYS_SUCCEEDS(insertStmt->Reset()); } else { rv = connection->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO repository (id, name) " - "VALUES (:id, :name)"), + nsLiteralCString("INSERT INTO repository (id, name) " + "VALUES (:id, :name)"), getter_AddRefs(insertStmt)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } - rv = insertStmt->BindInt32ByName(NS_LITERAL_CSTRING("id"), - persistenceType); + rv = insertStmt->BindInt32ByName("id"_ns, persistenceType); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } rv = insertStmt->BindUTF8StringByName( - NS_LITERAL_CSTRING("name"), - PersistenceTypeToString(persistenceType)); + "name"_ns, PersistenceTypeToString(persistenceType)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -8000,19 +7989,18 @@ nsresult OriginInfo::LockedBindToStatement( AssertCurrentThreadOwnsQuotaMutex(); MOZ_ASSERT(mGroupInfo); - nsresult rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("repository_id"), + nsresult rv = aStatement->BindInt32ByName("repository_id"_ns, mGroupInfo->mPersistenceType); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindUTF8StringByName(NS_LITERAL_CSTRING("origin"), mOrigin); + rv = aStatement->BindUTF8StringByName("origin"_ns, mOrigin); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindUTF8StringByName(NS_LITERAL_CSTRING("group_"), - mGroupInfo->mGroup); + rv = aStatement->BindUTF8StringByName("group_"_ns, mGroupInfo->mGroup); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -8020,29 +8008,27 @@ nsresult OriginInfo::LockedBindToStatement( nsCString clientUsagesText; mClientUsages.Serialize(clientUsagesText); - rv = aStatement->BindUTF8StringByName(NS_LITERAL_CSTRING("client_usages"), - clientUsagesText); + rv = aStatement->BindUTF8StringByName("client_usages"_ns, clientUsagesText); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("usage"), mUsage); + rv = aStatement->BindInt64ByName("usage"_ns, mUsage); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("last_access_time"), - mAccessTime); + rv = aStatement->BindInt64ByName("last_access_time"_ns, mAccessTime); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("accessed"), mAccessed); + rv = aStatement->BindInt32ByName("accessed"_ns, mAccessed); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("persisted"), mPersisted); + rv = aStatement->BindInt32ByName("persisted"_ns, mPersisted); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -11723,7 +11709,7 @@ nsresult UpgradeStorageFrom1_0To2_0Helper::MaybeRemoveMorgueDirectory( return rv; } - rv = morgueDir->Append(NS_LITERAL_STRING("morgue")); + rv = morgueDir->Append(u"morgue"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/dom/quota/InitializationTypes.h b/dom/quota/InitializationTypes.h index 54fc3a356285..b1a6d412086d 100644 --- a/dom/quota/InitializationTypes.h +++ b/dom/quota/InitializationTypes.h @@ -90,27 +90,27 @@ class InitializationInfo final { const Initialization aInitialization) { switch (aInitialization) { case Initialization::Storage: - return NS_LITERAL_CSTRING("Storage"); + return "Storage"_ns; case Initialization::TemporaryStorage: - return NS_LITERAL_CSTRING("TemporaryStorage"); + return "TemporaryStorage"_ns; case Initialization::DefaultRepository: - return NS_LITERAL_CSTRING("DefaultRepository"); + return "DefaultRepository"_ns; case Initialization::TemporaryRepository: - return NS_LITERAL_CSTRING("TemporaryRepository"); + return "TemporaryRepository"_ns; case Initialization::UpgradeStorageFrom0_0To1_0: - return NS_LITERAL_CSTRING("UpgradeStorageFrom0_0To1_0"); + return "UpgradeStorageFrom0_0To1_0"_ns; case Initialization::UpgradeStorageFrom1_0To2_0: - return NS_LITERAL_CSTRING("UpgradeStorageFrom1_0To2_0"); + return "UpgradeStorageFrom1_0To2_0"_ns; case Initialization::UpgradeStorageFrom2_0To2_1: - return NS_LITERAL_CSTRING("UpgradeStorageFrom2_0To2_1"); + return "UpgradeStorageFrom2_0To2_1"_ns; case Initialization::UpgradeStorageFrom2_1To2_2: - return NS_LITERAL_CSTRING("UpgradeStorageFrom2_1To2_2"); + return "UpgradeStorageFrom2_1To2_2"_ns; case Initialization::UpgradeStorageFrom2_2To2_3: - return NS_LITERAL_CSTRING("UpgradeStorageFrom2_2To2_3"); + return "UpgradeStorageFrom2_2To2_3"_ns; case Initialization::UpgradeFromIndexedDBDirectory: - return NS_LITERAL_CSTRING("UpgradeFromIndexedDBDirectory"); + return "UpgradeFromIndexedDBDirectory"_ns; case Initialization::UpgradeFromPersistentStorageDirectory: - return NS_LITERAL_CSTRING("UpgradeFromPersistentStorageDirectory"); + return "UpgradeFromPersistentStorageDirectory"_ns; default: MOZ_CRASH("Bad initialization value!"); diff --git a/dom/quota/QuotaCommon.cpp b/dom/quota/QuotaCommon.cpp index d61c6f06f1b7..a21e8c3e1ab8 100644 --- a/dom/quota/QuotaCommon.cpp +++ b/dom/quota/QuotaCommon.cpp @@ -24,10 +24,10 @@ namespace quota { namespace { #ifdef DEBUG -constexpr auto kDSStoreFileName = NS_LITERAL_STRING(".DS_Store"); -constexpr auto kDesktopFileName = NS_LITERAL_STRING(".desktop"); -constexpr auto kDesktopIniFileName = NS_LITERAL_STRING("desktop.ini"); -constexpr auto kThumbsDbFileName = NS_LITERAL_STRING("thumbs.db"); +constexpr auto kDSStoreFileName = u".DS_Store"_ns; +constexpr auto kDesktopFileName = u".desktop"_ns; +constexpr auto kDesktopIniFileName = u"desktop.ini"_ns; +constexpr auto kThumbsDbFileName = u"thumbs.db"_ns; #endif #ifdef XP_WIN diff --git a/dom/quota/QuotaCommon.h b/dom/quota/QuotaCommon.h index 401d07173c9b..53c3a43367a2 100644 --- a/dom/quota/QuotaCommon.h +++ b/dom/quota/QuotaCommon.h @@ -171,7 +171,7 @@ void StringifyTableKeys(const T& aTable, nsACString& aResult) { if (first) { first = false; } else { - aResult.Append(NS_LITERAL_CSTRING(", ")); + aResult.Append(", "_ns); } const auto& key = iter.Get()->GetKey(); diff --git a/dom/quota/StorageManager.cpp b/dom/quota/StorageManager.cpp index 4315cf310712..a1ccdfa90ace 100644 --- a/dom/quota/StorageManager.cpp +++ b/dom/quota/StorageManager.cpp @@ -98,8 +98,8 @@ class EstimateWorkerMainThreadRunnable final : public WorkerMainThreadRunnable { public: EstimateWorkerMainThreadRunnable(WorkerPrivate* aWorkerPrivate, PromiseWorkerProxy* aProxy) - : WorkerMainThreadRunnable( - aWorkerPrivate, NS_LITERAL_CSTRING("StorageManager :: Estimate")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "StorageManager :: Estimate"_ns), mProxy(aProxy) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); @@ -116,8 +116,8 @@ class PersistedWorkerMainThreadRunnable final public: PersistedWorkerMainThreadRunnable(WorkerPrivate* aWorkerPrivate, PromiseWorkerProxy* aProxy) - : WorkerMainThreadRunnable( - aWorkerPrivate, NS_LITERAL_CSTRING("StorageManager :: Persisted")), + : WorkerMainThreadRunnable(aWorkerPrivate, + "StorageManager :: Persisted"_ns), mProxy(aProxy) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); @@ -140,8 +140,8 @@ class PersistentStoragePermissionRequest final nsPIDOMWindowInner* aWindow, Promise* aPromise) : ContentPermissionRequestBase(aPrincipal, aWindow, - NS_LITERAL_CSTRING("dom.storageManager"), - NS_LITERAL_CSTRING("persistent-storage")), + "dom.storageManager"_ns, + "persistent-storage"_ns), mPromise(aPromise) { MOZ_ASSERT(aWindow); MOZ_ASSERT(aPromise); diff --git a/dom/quota/test/gtest/TestQuotaManager.cpp b/dom/quota/test/gtest/TestQuotaManager.cpp index e7abaa5ba778..4df859c47ab1 100644 --- a/dom/quota/test/gtest/TestQuotaManager.cpp +++ b/dom/quota/test/gtest/TestQuotaManager.cpp @@ -98,7 +98,7 @@ TEST(QuotaManager, OriginScope) // Test each origin scope type against particular origins. { - originScope.SetFromOrigin(NS_LITERAL_CSTRING("http://www.mozilla.org")); + originScope.SetFromOrigin("http://www.mozilla.org"_ns); static const OriginTest tests[] = { {"http://www.mozilla.org", true}, @@ -111,7 +111,7 @@ TEST(QuotaManager, OriginScope) } { - originScope.SetFromPrefix(NS_LITERAL_CSTRING("http://www.mozilla.org")); + originScope.SetFromPrefix("http://www.mozilla.org"_ns); static const OriginTest tests[] = { {"http://www.mozilla.org", true}, @@ -145,7 +145,7 @@ TEST(QuotaManager, WarnIfUnknownFile) nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(base)); ASSERT_EQ(rv, NS_OK); - rv = base->Append(NS_LITERAL_STRING("mozquotatests")); + rv = base->Append(u"mozquotatests"_ns); ASSERT_EQ(rv, NS_OK); base->Remove(true); @@ -153,14 +153,14 @@ TEST(QuotaManager, WarnIfUnknownFile) rv = base->Create(nsIFile::DIRECTORY_TYPE, 0700); ASSERT_EQ(rv, NS_OK); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING("foo.bar"), true, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING(".DS_Store"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING(".desktop"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING("desktop.ini"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING("DESKTOP.INI"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING("thumbs.db"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING("THUMBS.DB"), false, true); - CheckUnknownFileEntry(*base, NS_LITERAL_STRING(".xyz"), false, true); + CheckUnknownFileEntry(*base, u"foo.bar"_ns, true, true); + CheckUnknownFileEntry(*base, u".DS_Store"_ns, false, true); + CheckUnknownFileEntry(*base, u".desktop"_ns, false, true); + CheckUnknownFileEntry(*base, u"desktop.ini"_ns, false, true); + CheckUnknownFileEntry(*base, u"DESKTOP.INI"_ns, false, true); + CheckUnknownFileEntry(*base, u"thumbs.db"_ns, false, true); + CheckUnknownFileEntry(*base, u"THUMBS.DB"_ns, false, true); + CheckUnknownFileEntry(*base, u".xyz"_ns, false, true); rv = base->Remove(true); ASSERT_EQ(rv, NS_OK); diff --git a/dom/reporting/CrashReport.cpp b/dom/reporting/CrashReport.cpp index f7fdd496cb58..4cc44a6b8b42 100644 --- a/dom/reporting/CrashReport.cpp +++ b/dom/reporting/CrashReport.cpp @@ -31,8 +31,8 @@ bool CrashReport::Deliver(nsIPrincipal* aPrincipal, bool aIsOOM) { MOZ_ASSERT(aPrincipal); nsAutoCString endpoint_url; - ReportingHeader::GetEndpointForReport(NS_LITERAL_STRING("default"), - aPrincipal, endpoint_url); + ReportingHeader::GetEndpointForReport(u"default"_ns, aPrincipal, + endpoint_url); if (endpoint_url.IsEmpty()) { return false; } @@ -41,8 +41,8 @@ bool CrashReport::Deliver(nsIPrincipal* aPrincipal, bool aIsOOM) { aPrincipal->GetExposableSpec(safe_origin_spec); ReportDeliver::ReportData data; - data.mType = NS_LITERAL_STRING("crash"); - data.mGroupName = NS_LITERAL_STRING("default"); + data.mType = u"crash"_ns; + data.mGroupName = u"default"_ns; data.mURL = NS_ConvertUTF8toUTF16(safe_origin_spec); data.mCreationTime = TimeStamp::Now(); diff --git a/dom/reporting/ReportDeliver.cpp b/dom/reporting/ReportDeliver.cpp index 8bdd45fc1711..bd17ce7226c9 100644 --- a/dom/reporting/ReportDeliver.cpp +++ b/dom/reporting/ReportDeliver.cpp @@ -173,8 +173,7 @@ void SendReports(nsTArray& aReports, IgnoredErrorResult error; RefPtr internalHeaders = new InternalHeaders(HeadersGuardEnum::Request); - internalHeaders->Set(NS_LITERAL_CSTRING("Content-Type"), - NS_LITERAL_CSTRING("application/reports+json"), error); + internalHeaders->Set("Content-Type"_ns, "application/reports+json"_ns, error); if (NS_WARN_IF(error.Failed())) { return; } @@ -206,7 +205,7 @@ void SendReports(nsTArray& aReports, auto internalRequest = MakeSafeRefPtr(uriSpec, uriFragment); - internalRequest->SetMethod(NS_LITERAL_CSTRING("POST")); + internalRequest->SetMethod("POST"_ns); internalRequest->SetBody(streamBody, body.Length()); internalRequest->SetHeaders(internalHeaders); internalRequest->SetSkipServiceWorker(); diff --git a/dom/reporting/ReportingHeader.cpp b/dom/reporting/ReportingHeader.cpp index e7440583e1a6..d14e396c6ef6 100644 --- a/dom/reporting/ReportingHeader.cpp +++ b/dom/reporting/ReportingHeader.cpp @@ -166,8 +166,7 @@ void ReportingHeader::ReportingFromChannel(nsIHttpChannel* aChannel) { } nsAutoCString headerValue; - rv = - aChannel->GetResponseHeader(NS_LITERAL_CSTRING("Report-To"), headerValue); + rv = aChannel->GetResponseHeader("Report-To"_ns, headerValue); if (NS_FAILED(rv)) { return; } @@ -464,8 +463,7 @@ void ReportingHeader::LogToConsoleInternal(nsIHttpChannel* aChannel, } rv = nsContentUtils::ReportToConsoleByWindowID( - localizedMsg, nsIScriptError::infoFlag, NS_LITERAL_CSTRING("Reporting"), - windowID, aURI); + localizedMsg, nsIScriptError::infoFlag, "Reporting"_ns, windowID, aURI); Unused << NS_WARN_IF(NS_FAILED(rv)); } diff --git a/dom/reporting/tests/gtest/TestReportToParser.cpp b/dom/reporting/tests/gtest/TestReportToParser.cpp index 0bce790a5e6b..a3549886a3ba 100644 --- a/dom/reporting/tests/gtest/TestReportToParser.cpp +++ b/dom/reporting/tests/gtest/TestReportToParser.cpp @@ -23,22 +23,21 @@ TEST(ReportToParser, Basic) // Empty header. UniquePtr client = - ReportingHeader::ParseHeader(nullptr, uri, NS_LITERAL_CSTRING("")); + ReportingHeader::ParseHeader(nullptr, uri, ""_ns); ASSERT_TRUE(!client); // Empty header. - client = - ReportingHeader::ParseHeader(nullptr, uri, NS_LITERAL_CSTRING(" ")); + client = ReportingHeader::ParseHeader(nullptr, uri, " "_ns); ASSERT_TRUE(!client); // No minimal attributes - client = ReportingHeader::ParseHeader(nullptr, uri, NS_LITERAL_CSTRING("{}")); + client = ReportingHeader::ParseHeader(nullptr, uri, "{}"_ns); ASSERT_TRUE(!client); // Single client client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 42, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); ASSERT_TRUE(!!client); @@ -60,7 +59,7 @@ TEST(ReportToParser, Basic) // 2 clients, same group name. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 43, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 44, \"endpoints\": [{\"url\": " @@ -73,7 +72,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first one with an invalid group name. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 43, \"group\": 123, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 44, \"endpoints\": [{\"url\": " @@ -86,7 +85,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first one with an invalid group name. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 43, \"group\": null, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 44, \"endpoints\": [{\"url\": " @@ -99,7 +98,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first one with an invalid group name. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 43, \"group\": {}, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 44, \"endpoints\": [{\"url\": " @@ -112,7 +111,7 @@ TEST(ReportToParser, Basic) // Single client: optional params client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 45, \"group\": \"foobar\", \"include_subdomains\": " "true, \"endpoints\": [{\"url\": \"https://example.com\", " "\"priority\": 1, \"weight\": 2}]}")); @@ -125,7 +124,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: missing max_age. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"endpoints\": [{\"url\": \"https://example.com\", \"priority\": " "1, \"weight\": 2}]}," "{\"max_age\": 46, \"endpoints\": [{\"url\": " @@ -137,7 +136,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid max_age. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": null, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 46, \"endpoints\": [{\"url\": " @@ -149,7 +148,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid max_age. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": \"foobar\", \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 46, \"endpoints\": [{\"url\": " @@ -161,7 +160,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid max_age. client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": {}, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}," "{\"max_age\": 46, \"endpoints\": [{\"url\": " @@ -173,7 +172,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: missing endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 47}," "{\"max_age\": 48, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -184,7 +183,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 47, \"endpoints\": null }," "{\"max_age\": 48, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -195,7 +194,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 47, \"endpoints\": \"abc\" }," "{\"max_age\": 48, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -206,7 +205,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 47, \"endpoints\": 42 }," "{\"max_age\": 48, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -217,7 +216,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: invalid endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 47, \"endpoints\": {} }," "{\"max_age\": 48, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -228,7 +227,7 @@ TEST(ReportToParser, Basic) // 2 clients, the first incomplete: empty endpoints client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 49, \"endpoints\": []}," "{\"max_age\": 50, \"endpoints\": [{\"url\": " "\"https://example.com\", \"priority\": 1, \"weight\": 2}]}")); @@ -239,10 +238,10 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: missing url client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 51, \"endpoints\": [" - " {\"priority\": 1, \"weight\": 2}," - " {\"url\": \"https://example.com\", \"priority\": 1, " - "\"weight\": 2}]}")); + nsLiteralCString("{\"max_age\": 51, \"endpoints\": [" + " {\"priority\": 1, \"weight\": 2}," + " {\"url\": \"https://example.com\", \"priority\": 1, " + "\"weight\": 2}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -259,10 +258,10 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid url client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 51, \"endpoints\": [" - " {\"url\": 42, \"priority\": 1, \"weight\": 2}," - " {\"url\": \"https://example.com\", \"priority\": 1, " - "\"weight\": 2}]}")); + nsLiteralCString("{\"max_age\": 51, \"endpoints\": [" + " {\"url\": 42, \"priority\": 1, \"weight\": 2}," + " {\"url\": \"https://example.com\", \"priority\": 1, " + "\"weight\": 2}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -279,7 +278,7 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid url client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 51, \"endpoints\": [" " {\"url\": \"something here\", \"priority\": 1, \"weight\": 2}," " {\"url\": \"https://example.com\", \"priority\": 1, \"weight\": " @@ -300,10 +299,10 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid url client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 51, \"endpoints\": [" - " {\"url\": {}, \"priority\": 1, \"weight\": 2}," - " {\"url\": \"https://example.com\", \"priority\": 1, " - "\"weight\": 2}]}")); + nsLiteralCString("{\"max_age\": 51, \"endpoints\": [" + " {\"url\": {}, \"priority\": 1, \"weight\": 2}," + " {\"url\": \"https://example.com\", \"priority\": 1, " + "\"weight\": 2}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -320,9 +319,8 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: missing priority client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( - "{\"max_age\": 52, \"endpoints\": [" - " {\"url\": \"https://example.com\", \"weight\": 3}]}")); + nsLiteralCString("{\"max_age\": 52, \"endpoints\": [" + " {\"url\": \"https://example.com\", \"weight\": 3}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -339,11 +337,11 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid priority client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 52, \"endpoints\": [" - " {\"url\": \"https://example.com\", \"priority\": " - "{}, \"weight\": 2}," - " {\"url\": \"https://example.com\", \"priority\": 2, " - "\"weight\": 3}]}")); + nsLiteralCString("{\"max_age\": 52, \"endpoints\": [" + " {\"url\": \"https://example.com\", \"priority\": " + "{}, \"weight\": 2}," + " {\"url\": \"https://example.com\", \"priority\": 2, " + "\"weight\": 3}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -360,11 +358,11 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid priority client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 52, \"endpoints\": [" - " {\"url\": \"https://example.com\", \"priority\": " - "\"ok\", \"weight\": 2}," - " {\"url\": \"https://example.com\", \"priority\": 2, " - "\"weight\": 3}]}")); + nsLiteralCString("{\"max_age\": 52, \"endpoints\": [" + " {\"url\": \"https://example.com\", \"priority\": " + "\"ok\", \"weight\": 2}," + " {\"url\": \"https://example.com\", \"priority\": 2, " + "\"weight\": 3}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); @@ -381,7 +379,7 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: missing weight client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING( + nsLiteralCString( "{\"max_age\": 52, \"endpoints\": [" " {\"url\": \"https://example.com\", \"priority\": 5}]}")); ASSERT_TRUE(!!client); @@ -400,11 +398,11 @@ TEST(ReportToParser, Basic) // 2 endpoints, the first incomplete: invalid weight client = ReportingHeader::ParseHeader( nullptr, uri, - NS_LITERAL_CSTRING("{\"max_age\": 52, \"endpoints\": [" - " {\"url\": \"https://example.com\", \"priority\": 4, " - "\"weight\": []}," - " {\"url\": \"https://example.com\", \"priority\": 5, " - "\"weight\": 6}]}")); + nsLiteralCString("{\"max_age\": 52, \"endpoints\": [" + " {\"url\": \"https://example.com\", \"priority\": 4, " + "\"weight\": []}," + " {\"url\": \"https://example.com\", \"priority\": 5, " + "\"weight\": 6}]}")); ASSERT_TRUE(!!client); ASSERT_EQ((uint32_t)1, client->mGroups.Length()); ASSERT_EQ((uint32_t)1, client->mGroups.ElementAt(0).mEndpoints.Length()); diff --git a/dom/script/ScriptElement.cpp b/dom/script/ScriptElement.cpp index c8524b6c75d6..561c58fcc24f 100644 --- a/dom/script/ScriptElement.cpp +++ b/dom/script/ScriptElement.cpp @@ -40,9 +40,8 @@ ScriptElement::ScriptAvailable(nsresult aResult, nsIScriptElement* aElement, nsresult ScriptElement::FireErrorEvent() { nsCOMPtr cont = do_QueryInterface((nsIScriptElement*)this); - return nsContentUtils::DispatchTrustedEvent(cont->OwnerDoc(), cont, - NS_LITERAL_STRING("error"), - CanBubble::eNo, Cancelable::eNo); + return nsContentUtils::DispatchTrustedEvent( + cont->OwnerDoc(), cont, u"error"_ns, CanBubble::eNo, Cancelable::eNo); } NS_IMETHODIMP diff --git a/dom/script/ScriptLoader.cpp b/dom/script/ScriptLoader.cpp index 626e82c4a44c..14082f2afd96 100644 --- a/dom/script/ScriptLoader.cpp +++ b/dom/script/ScriptLoader.cpp @@ -308,7 +308,7 @@ static bool IsScriptEventHandler(ScriptKind kind, nsIContent* aScriptElement) { // We found for="window", now check for event="onload". const nsAString& event_str = nsContentUtils::TrimWhitespace(eventAttr, false); - if (!StringBeginsWith(event_str, NS_LITERAL_STRING("onload"), + if (!StringBeginsWith(event_str, u"onload"_ns, nsCaseInsensitiveStringComparator)) { // It ain't "onload.*". @@ -682,9 +682,9 @@ static already_AddRefed ResolveModuleSpecifier( return nullptr; } - if (!StringBeginsWith(aSpecifier, NS_LITERAL_STRING("/")) && - !StringBeginsWith(aSpecifier, NS_LITERAL_STRING("./")) && - !StringBeginsWith(aSpecifier, NS_LITERAL_STRING("../"))) { + if (!StringBeginsWith(aSpecifier, u"/"_ns) && + !StringBeginsWith(aSpecifier, u"./"_ns) && + !StringBeginsWith(aSpecifier, u"../"_ns)) { return nullptr; } @@ -1473,8 +1473,7 @@ nsresult ScriptLoader::StartLoad(ScriptLoadRequest* aRequest) { aRequest->ShouldAcceptBinASTEncoding()) { acceptTypes = APPLICATION_JAVASCRIPT_BINAST ", */*"; } - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), - acceptTypes, false); + rv = httpChannel->SetRequestHeader("Accept"_ns, acceptTypes, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); nsCOMPtr referrerInfo = @@ -1500,9 +1499,9 @@ nsresult ScriptLoader::StartLoad(ScriptLoadRequest* aRequest) { nsCOMPtr timedChannel(do_QueryInterface(httpChannel)); if (timedChannel) { if (aRequest->IsLinkPreloadScript()) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("link")); + timedChannel->SetInitiatorType(u"link"_ns); } else { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("script")); + timedChannel->SetInitiatorType(u"script"_ns); } } @@ -2480,9 +2479,8 @@ nsresult ScriptLoader::ProcessRequest(ScriptLoadRequest* aRequest) { bool runScript = !!pwin; if (runScript) { nsContentUtils::DispatchTrustedEvent( - scriptElem->OwnerDoc(), scriptElem, - NS_LITERAL_STRING("beforescriptexecute"), CanBubble::eYes, - Cancelable::eYes, &runScript); + scriptElem->OwnerDoc(), scriptElem, u"beforescriptexecute"_ns, + CanBubble::eYes, Cancelable::eYes, &runScript); } // Inner window could have gone away after firing beforescriptexecute @@ -2501,10 +2499,9 @@ nsresult ScriptLoader::ProcessRequest(ScriptLoadRequest* aRequest) { doc->DecrementIgnoreDestructiveWritesCounter(); } - nsContentUtils::DispatchTrustedEvent( - scriptElem->OwnerDoc(), scriptElem, - NS_LITERAL_STRING("afterscriptexecute"), CanBubble::eYes, - Cancelable::eNo); + nsContentUtils::DispatchTrustedEvent(scriptElem->OwnerDoc(), scriptElem, + u"afterscriptexecute"_ns, + CanBubble::eYes, Cancelable::eNo); } FireScriptEvaluated(rv, aRequest); @@ -3568,9 +3565,9 @@ void ScriptLoader::ReportErrorToConsole(ScriptLoadRequest* aRequest, uint32_t columnNo = element ? element->GetScriptColumnNumber() : 0; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Script Loader"), - mDocument, nsContentUtils::eDOM_PROPERTIES, message, params, nullptr, - EmptyString(), lineNo, columnNo); + nsIScriptError::warningFlag, "Script Loader"_ns, mDocument, + nsContentUtils::eDOM_PROPERTIES, message, params, nullptr, EmptyString(), + lineNo, columnNo); } void ScriptLoader::ReportPreloadErrorsToConsole(ScriptLoadRequest* aRequest) { diff --git a/dom/security/CSPEvalChecker.cpp b/dom/security/CSPEvalChecker.cpp index 6e1723805bae..c95b8e1d0568 100644 --- a/dom/security/CSPEvalChecker.cpp +++ b/dom/security/CSPEvalChecker.cpp @@ -74,8 +74,7 @@ class WorkerCSPCheckRunnable final : public WorkerMainThreadRunnable { const nsAString& aExpression, const nsAString& aFileNameString, uint32_t aLineNum, uint32_t aColumnNum) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("CSP Eval Check")), + : WorkerMainThreadRunnable(aWorkerPrivate, "CSP Eval Check"_ns), mExpression(aExpression), mFileNameString(aFileNameString), mLineNum(aLineNum), diff --git a/dom/security/DOMSecurityMonitor.cpp b/dom/security/DOMSecurityMonitor.cpp index d6af97f60da8..3bb109d41662 100644 --- a/dom/security/DOMSecurityMonitor.cpp +++ b/dom/security/DOMSecurityMonitor.cpp @@ -50,41 +50,39 @@ void DOMSecurityMonitor::AuditParsingOfHTMLXMLFragments( * withiout proper review from a dom:security peer! */ static nsLiteralCString htmlFragmentAllowlist[] = { - NS_LITERAL_CSTRING("chrome://global/content/elements/marquee.js"), - NS_LITERAL_CSTRING( + "chrome://global/content/elements/marquee.js"_ns, + nsLiteralCString( "chrome://pocket/content/panels/js/vendor/jquery-2.1.1.min.js"), - NS_LITERAL_CSTRING("chrome://browser/content/aboutNetError.js"), - NS_LITERAL_CSTRING("chrome://devtools/content/shared/sourceeditor/" - "codemirror/codemirror.bundle.js"), - NS_LITERAL_CSTRING( + "chrome://browser/content/aboutNetError.js"_ns, + nsLiteralCString("chrome://devtools/content/shared/sourceeditor/" + "codemirror/codemirror.bundle.js"), + nsLiteralCString( "chrome://devtools-startup/content/aboutdevtools/aboutdevtools.js"), - NS_LITERAL_CSTRING( + nsLiteralCString( "resource://activity-stream/data/content/activity-stream.bundle.js"), - NS_LITERAL_CSTRING("resource://devtools/client/debugger/src/components/" - "Editor/Breakpoint.js"), - NS_LITERAL_CSTRING("resource://devtools/client/debugger/src/components/" - "Editor/ColumnBreakpoint.js"), - NS_LITERAL_CSTRING( + nsLiteralCString("resource://devtools/client/debugger/src/components/" + "Editor/Breakpoint.js"), + nsLiteralCString("resource://devtools/client/debugger/src/components/" + "Editor/ColumnBreakpoint.js"), + nsLiteralCString( "resource://devtools/client/shared/vendor/fluent-react.js"), - NS_LITERAL_CSTRING( - "resource://devtools/client/shared/vendor/react-dom.js"), - NS_LITERAL_CSTRING( + "resource://devtools/client/shared/vendor/react-dom.js"_ns, + nsLiteralCString( "resource://devtools/client/shared/vendor/react-dom-dev.js"), - NS_LITERAL_CSTRING( + nsLiteralCString( "resource://devtools/client/shared/widgets/FilterWidget.js"), - NS_LITERAL_CSTRING("resource://devtools/client/shared/widgets/tooltip/" - "inactive-css-tooltip-helper.js"), - NS_LITERAL_CSTRING( - "resource://devtools/client/shared/widgets/Spectrum.js"), - NS_LITERAL_CSTRING("resource://gre/modules/narrate/VoiceSelect.jsm"), - NS_LITERAL_CSTRING("resource://normandy-vendor/ReactDOM.js"), + nsLiteralCString("resource://devtools/client/shared/widgets/tooltip/" + "inactive-css-tooltip-helper.js"), + "resource://devtools/client/shared/widgets/Spectrum.js"_ns, + "resource://gre/modules/narrate/VoiceSelect.jsm"_ns, + "resource://normandy-vendor/ReactDOM.js"_ns, // ------------------------------------------------------------------ // test pages // ------------------------------------------------------------------ - NS_LITERAL_CSTRING("chrome://mochikit/content/harness.xhtml"), - NS_LITERAL_CSTRING("chrome://mochikit/content/tests/"), - NS_LITERAL_CSTRING("chrome://mochitests/content/"), - NS_LITERAL_CSTRING("chrome://reftest/content/"), + "chrome://mochikit/content/harness.xhtml"_ns, + "chrome://mochikit/content/tests/"_ns, + "chrome://mochitests/content/"_ns, + "chrome://reftest/content/"_ns, }; for (const nsLiteralCString& allowlistEntry : htmlFragmentAllowlist) { diff --git a/dom/security/FramingChecker.cpp b/dom/security/FramingChecker.cpp index 364948b20b3e..29d0e0468881 100644 --- a/dom/security/FramingChecker.cpp +++ b/dom/security/FramingChecker.cpp @@ -51,8 +51,7 @@ void FramingChecker::ReportError(const char* aMessageTag, params.AppendElement(aPolicy); params.AppendElement(NS_ConvertUTF8toUTF16(spec)); - httpChannel->AddConsoleReport(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("X-Frame-Options"), + httpChannel->AddConsoleReport(nsIScriptError::errorFlag, "X-Frame-Options"_ns, nsContentUtils::eSECURITY_PROPERTIES, spec, 0, 0, nsDependentCString(aMessageTag), params); } @@ -148,16 +147,16 @@ static bool ShouldIgnoreFrameOptions(nsIChannel* aChannel, nsCOMPtr loadInfo = aChannel->LoadInfo(); uint64_t innerWindowID = loadInfo->GetInnerWindowID(); bool privateWindow = !!loadInfo->GetOriginAttributes().mPrivateBrowsingId; - AutoTArray params = {NS_LITERAL_STRING("x-frame-options"), - NS_LITERAL_STRING("frame-ancestors")}; + AutoTArray params = {u"x-frame-options"_ns, + u"frame-ancestors"_ns}; CSP_LogLocalizedStr("IgnoringSrcBecauseOfDirective", params, EmptyString(), // no sourcefile EmptyString(), // no scriptsample 0, // no linenumber 0, // no columnnumber nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("IgnoringSrcBecauseOfDirective"), - innerWindowID, privateWindow); + "IgnoringSrcBecauseOfDirective"_ns, innerWindowID, + privateWindow); return true; } @@ -213,8 +212,8 @@ bool FramingChecker::CheckFrameOptions(nsIChannel* aChannel, } nsAutoCString xfoHeaderCValue; - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("X-Frame-Options"), xfoHeaderCValue); + Unused << httpChannel->GetResponseHeader("X-Frame-Options"_ns, + xfoHeaderCValue); NS_ConvertUTF8toUTF16 xfoHeaderValue(xfoHeaderCValue); // if no header value, there's nothing to do. diff --git a/dom/security/ReferrerInfo.cpp b/dom/security/ReferrerInfo.cpp index 778b3982c374..2fa543dd4858 100644 --- a/dom/security/ReferrerInfo.cpp +++ b/dom/security/ReferrerInfo.cpp @@ -333,7 +333,7 @@ nsresult ReferrerInfo::HandleUserXOriginSendingPolicy(nsIURI* aURI, // Send an empty referrer if xorigin and leaving a .onion domain. if (StaticPrefs::network_http_referer_hideOnionSource() && !uriHost.Equals(referrerHost) && - StringEndsWith(referrerHost, NS_LITERAL_CSTRING(".onion"))) { + StringEndsWith(referrerHost, ".onion"_ns)) { return NS_OK; } @@ -411,7 +411,7 @@ bool ReferrerInfo::ShouldSetNullOriginHeader(net::HttpBaseChannel* aChannel, if (StaticPrefs::network_http_referer_hideOnionSource()) { nsAutoCString host; if (NS_SUCCEEDED(aOriginURI->GetAsciiHost(host)) && - StringEndsWith(host, NS_LITERAL_CSTRING(".onion"))) { + StringEndsWith(host, ".onion"_ns)) { return ReferrerInfo::IsCrossOriginRequest(aChannel); } } @@ -702,8 +702,7 @@ void ReferrerInfo::LogMessageToConsole( } rv = nsContentUtils::ReportToConsoleByWindowID( - localizedMsg, nsIScriptError::infoFlag, NS_LITERAL_CSTRING("Security"), - windowID, uri); + localizedMsg, nsIScriptError::infoFlag, "Security"_ns, windowID, uri); Unused << NS_WARN_IF(NS_FAILED(rv)); } diff --git a/dom/security/SRICheck.cpp b/dom/security/SRICheck.cpp index 174f7de0ba9b..8f57bcb14987 100644 --- a/dom/security/SRICheck.cpp +++ b/dom/security/SRICheck.cpp @@ -79,10 +79,9 @@ static nsresult IsEligible(nsIChannel* aChannel, nsTArray params; params.AppendElement(requestSpecUTF16); aReporter->AddConsoleReport( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::errorFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("IneligibleResource"), - const_cast&>(params)); + "IneligibleResource"_ns, const_cast&>(params)); return NS_ERROR_SRI_NOT_ELIGIBLE; } @@ -122,10 +121,9 @@ nsresult SRICheck::IntegrityMetadata(const nsAString& aMetadataList, nsTArray params; params.AppendElement(tokenUTF16); aReporter->AddConsoleReport( - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::warningFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("MalformedIntegrityHash"), + "MalformedIntegrityHash"_ns, const_cast&>(params)); } else if (!metadata.IsAlgorithmSupported()) { nsAutoCString alg; @@ -134,10 +132,9 @@ nsresult SRICheck::IntegrityMetadata(const nsAString& aMetadataList, nsTArray params; params.AppendElement(algUTF16); aReporter->AddConsoleReport( - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::warningFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("UnsupportedHashAlg"), + "UnsupportedHashAlg"_ns, const_cast&>(params)); } @@ -194,12 +191,10 @@ SRICheckDataVerifier::SRICheckDataVerifier(const SRIMetadata& aMetadata, if (!aMetadata.IsValid()) { nsTArray params; - aReporter->AddConsoleReport(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Sub-resource Integrity"), - nsContentUtils::eSECURITY_PROPERTIES, - aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("NoValidMetadata"), - const_cast&>(params)); + aReporter->AddConsoleReport( + nsIScriptError::warningFlag, "Sub-resource Integrity"_ns, + nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, + "NoValidMetadata"_ns, const_cast&>(params)); mInvalidMetadata = true; return; // ignore invalid metadata for forward-compatibility } @@ -270,9 +265,9 @@ nsresult SRICheckDataVerifier::VerifyHash( if (NS_WARN_IF(NS_FAILED(Base64Decode(base64Hash, binaryHash)))) { nsTArray params; aReporter->AddConsoleReport( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::errorFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("InvalidIntegrityBase64"), + "InvalidIntegrityBase64"_ns, const_cast&>(params)); return NS_ERROR_SRI_CORRUPT; } @@ -283,9 +278,9 @@ nsresult SRICheckDataVerifier::VerifyHash( if (binaryHash.Length() != hashLength) { nsTArray params; aReporter->AddConsoleReport( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::errorFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("InvalidIntegrityLength"), + "InvalidIntegrityLength"_ns, const_cast&>(params)); return NS_ERROR_SRI_CORRUPT; } @@ -350,10 +345,9 @@ nsresult SRICheckDataVerifier::Verify(const SRIMetadata& aMetadata, nsTArray params; params.AppendElement(algUTF16); aReporter->AddConsoleReport( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Sub-resource Integrity"), + nsIScriptError::errorFlag, "Sub-resource Integrity"_ns, nsContentUtils::eSECURITY_PROPERTIES, aSourceFileURI, 0, 0, - NS_LITERAL_CSTRING("IntegrityMismatch"), - const_cast&>(params)); + "IntegrityMismatch"_ns, const_cast&>(params)); return NS_ERROR_SRI_CORRUPT; } diff --git a/dom/security/SecFetch.cpp b/dom/security/SecFetch.cpp index 707c1ea0190b..5cf61f7a4ef8 100644 --- a/dom/security/SecFetch.cpp +++ b/dom/security/SecFetch.cpp @@ -17,94 +17,94 @@ nsCString MapInternalContentPolicyTypeToDest(nsContentPolicyType aType) { switch (aType) { case nsIContentPolicy::TYPE_OTHER: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_INTERNAL_SCRIPT: case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD: case nsIContentPolicy::TYPE_INTERNAL_MODULE: case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD: case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS: case nsIContentPolicy::TYPE_SCRIPT: - return NS_LITERAL_CSTRING("script"); + return "script"_ns; case nsIContentPolicy::TYPE_INTERNAL_WORKER: - return NS_LITERAL_CSTRING("worker"); + return "worker"_ns; case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER: - return NS_LITERAL_CSTRING("sharedworker"); + return "sharedworker"_ns; case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER: - return NS_LITERAL_CSTRING("serviceworker"); + return "serviceworker"_ns; case nsIContentPolicy::TYPE_INTERNAL_AUDIOWORKLET: - return NS_LITERAL_CSTRING("audioworklet"); + return "audioworklet"_ns; case nsIContentPolicy::TYPE_INTERNAL_PAINTWORKLET: - return NS_LITERAL_CSTRING("paintworklet"); + return "paintworklet"_ns; case nsIContentPolicy::TYPE_IMAGESET: case nsIContentPolicy::TYPE_INTERNAL_IMAGE: case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD: case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON: case nsIContentPolicy::TYPE_IMAGE: - return NS_LITERAL_CSTRING("image"); + return "image"_ns; case nsIContentPolicy::TYPE_STYLESHEET: case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET: case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD: - return NS_LITERAL_CSTRING("style"); + return "style"_ns; case nsIContentPolicy::TYPE_OBJECT: case nsIContentPolicy::TYPE_INTERNAL_OBJECT: - return NS_LITERAL_CSTRING("object"); + return "object"_ns; case nsIContentPolicy::TYPE_INTERNAL_EMBED: - return NS_LITERAL_CSTRING("embed"); + return "embed"_ns; case nsIContentPolicy::TYPE_DOCUMENT: - return NS_LITERAL_CSTRING("document"); + return "document"_ns; case nsIContentPolicy::TYPE_SUBDOCUMENT: case nsIContentPolicy::TYPE_INTERNAL_IFRAME: - return NS_LITERAL_CSTRING("iframe"); + return "iframe"_ns; case nsIContentPolicy::TYPE_INTERNAL_FRAME: - return NS_LITERAL_CSTRING("frame"); + return "frame"_ns; case nsIContentPolicy::TYPE_REFRESH: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_PING: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_XMLHTTPREQUEST: case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_OBJECT_SUBREQUEST: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_DTD: case nsIContentPolicy::TYPE_INTERNAL_DTD: case nsIContentPolicy::TYPE_INTERNAL_FORCE_ALLOWED_DTD: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_FONT: case nsIContentPolicy::TYPE_INTERNAL_FONT_PRELOAD: - return NS_LITERAL_CSTRING("font"); + return "font"_ns; case nsIContentPolicy::TYPE_MEDIA: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_INTERNAL_AUDIO: - return NS_LITERAL_CSTRING("audio"); + return "audio"_ns; case nsIContentPolicy::TYPE_INTERNAL_VIDEO: - return NS_LITERAL_CSTRING("video"); + return "video"_ns; case nsIContentPolicy::TYPE_INTERNAL_TRACK: - return NS_LITERAL_CSTRING("track"); + return "track"_ns; case nsIContentPolicy::TYPE_WEBSOCKET: - return NS_LITERAL_CSTRING("websocket"); + return "websocket"_ns; case nsIContentPolicy::TYPE_CSP_REPORT: - return NS_LITERAL_CSTRING("report"); + return "report"_ns; case nsIContentPolicy::TYPE_XSLT: - return NS_LITERAL_CSTRING("xslt"); + return "xslt"_ns; case nsIContentPolicy::TYPE_BEACON: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_FETCH: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_WEB_MANIFEST: - return NS_LITERAL_CSTRING("manifest"); + return "manifest"_ns; case nsIContentPolicy::TYPE_SAVEAS_DOWNLOAD: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; case nsIContentPolicy::TYPE_SPECULATIVE: - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; default: MOZ_CRASH("Unhandled nsContentPolicyType value"); break; } - return NS_LITERAL_CSTRING("empty"); + return "empty"_ns; } // Helper function to determine whether a request (including involved @@ -224,8 +224,8 @@ void SecFetch::AddSecFetchDest(nsIHttpChannel* aHTTPChannel) { nsContentPolicyType contentType = loadInfo->InternalContentPolicyType(); nsCString dest = MapInternalContentPolicyTypeToDest(contentType); - nsresult rv = aHTTPChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-Fetch-Dest"), dest, false); + nsresult rv = + aHTTPChannel->SetRequestHeader("Sec-Fetch-Dest"_ns, dest, false); Unused << NS_WARN_IF(NS_FAILED(rv)); } @@ -238,9 +238,9 @@ void SecFetch::AddSecFetchMode(nsIHttpChannel* aHTTPChannel) { if (securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_INHERITS || securityMode == nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED) { - mode = NS_LITERAL_CSTRING("same-origin"); + mode = "same-origin"_ns; } else if (securityMode == nsILoadInfo::SEC_REQUIRE_CORS_DATA_INHERITS) { - mode = NS_LITERAL_CSTRING("cors"); + mode = "cors"_ns; } else { // If it's not one of the security modes above, then we ensure it's // at least one of the others defined in nsILoadInfo @@ -254,13 +254,13 @@ void SecFetch::AddSecFetchMode(nsIHttpChannel* aHTTPChannel) { externalType == nsIContentPolicy::TYPE_SUBDOCUMENT || externalType == nsIContentPolicy::TYPE_REFRESH || externalType == nsIContentPolicy::TYPE_OBJECT) { - mode = NS_LITERAL_CSTRING("navigate"); + mode = "navigate"_ns; } else if (externalType == nsIContentPolicy::TYPE_WEBSOCKET) { - mode = NS_LITERAL_CSTRING("websocket"); + mode = "websocket"_ns; } - nsresult rv = aHTTPChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-Fetch-Mode"), mode, false); + nsresult rv = + aHTTPChannel->SetRequestHeader("Sec-Fetch-Mode"_ns, mode, false); Unused << NS_WARN_IF(NS_FAILED(rv)); } @@ -271,18 +271,18 @@ void SecFetch::AddSecFetchSite(nsIHttpChannel* aHTTPChannel) { if (!isSameOrigin) { bool isSameSite = IsSameSite(aHTTPChannel); if (isSameSite) { - site = NS_LITERAL_CSTRING("same-site"); + site = "same-site"_ns; } else { - site = NS_LITERAL_CSTRING("cross-site"); + site = "cross-site"_ns; } } if (IsUserTriggeredForSecFetchSite(aHTTPChannel)) { - site = NS_LITERAL_CSTRING("none"); + site = "none"_ns; } - nsresult rv = aHTTPChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-Fetch-Site"), site, false); + nsresult rv = + aHTTPChannel->SetRequestHeader("Sec-Fetch-Site"_ns, site, false); Unused << NS_WARN_IF(NS_FAILED(rv)); } @@ -302,8 +302,8 @@ void SecFetch::AddSecFetchUser(nsIHttpChannel* aHTTPChannel) { } nsAutoCString user("?1"); - nsresult rv = aHTTPChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-Fetch-User"), user, false); + nsresult rv = + aHTTPChannel->SetRequestHeader("Sec-Fetch-User"_ns, user, false); Unused << NS_WARN_IF(NS_FAILED(rv)); } diff --git a/dom/security/featurepolicy/FeaturePolicy.cpp b/dom/security/featurepolicy/FeaturePolicy.cpp index b1c7beb13692..bea1f296d3be 100644 --- a/dom/security/featurepolicy/FeaturePolicy.cpp +++ b/dom/security/featurepolicy/FeaturePolicy.cpp @@ -264,7 +264,7 @@ void FeaturePolicy::GetAllowlistForFeature(const nsAString& aFeatureName, for (const Feature& feature : mFeatures) { if (feature.Name().Equals(aFeatureName)) { if (feature.AllowsAll()) { - aList.AppendElement(NS_LITERAL_STRING("*")); + aList.AppendElement(u"*"_ns); return; } @@ -286,7 +286,7 @@ void FeaturePolicy::GetAllowlistForFeature(const nsAString& aFeatureName, switch (FeaturePolicyUtils::DefaultAllowListFeature(aFeatureName)) { case FeaturePolicyUtils::FeaturePolicyValue::eAll: - aList.AppendElement(NS_LITERAL_STRING("*")); + aList.AppendElement(u"*"_ns); return; case FeaturePolicyUtils::FeaturePolicyValue::eSelf: { diff --git a/dom/security/featurepolicy/FeaturePolicyParser.cpp b/dom/security/featurepolicy/FeaturePolicyParser.cpp index c8ac7b15eec9..57adac2b0aaf 100644 --- a/dom/security/featurepolicy/FeaturePolicyParser.cpp +++ b/dom/security/featurepolicy/FeaturePolicyParser.cpp @@ -27,8 +27,8 @@ void ReportToConsoleUnsupportedFeature(Document* aDocument, AutoTArray params = {aFeatureName}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Feature Policy"), - aDocument, nsContentUtils::eSECURITY_PROPERTIES, + nsIScriptError::warningFlag, "Feature Policy"_ns, aDocument, + nsContentUtils::eSECURITY_PROPERTIES, "FeaturePolicyUnsupportedFeatureName", params); } @@ -41,8 +41,8 @@ void ReportToConsoleInvalidEmptyAllowValue(Document* aDocument, AutoTArray params = {aFeatureName}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Feature Policy"), - aDocument, nsContentUtils::eSECURITY_PROPERTIES, + nsIScriptError::warningFlag, "Feature Policy"_ns, aDocument, + nsContentUtils::eSECURITY_PROPERTIES, "FeaturePolicyInvalidEmptyAllowValue", params); } @@ -54,10 +54,10 @@ void ReportToConsoleInvalidAllowValue(Document* aDocument, AutoTArray params = {aValue}; - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Feature Policy"), - aDocument, nsContentUtils::eSECURITY_PROPERTIES, - "FeaturePolicyInvalidAllowValue", params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, + "Feature Policy"_ns, aDocument, + nsContentUtils::eSECURITY_PROPERTIES, + "FeaturePolicyInvalidAllowValue", params); } } // namespace diff --git a/dom/security/featurepolicy/FeaturePolicyUtils.cpp b/dom/security/featurepolicy/FeaturePolicyUtils.cpp index 2f6bbdd93b3a..cdf7a6c85de2 100644 --- a/dom/security/featurepolicy/FeaturePolicyUtils.cpp +++ b/dom/security/featurepolicy/FeaturePolicyUtils.cpp @@ -242,11 +242,10 @@ void FeaturePolicyUtils::ReportViolation(Document* aDocument, RefPtr body = new FeaturePolicyViolationReportBody(window->AsGlobal(), aFeatureName, fileName, lineNumber, columnNumber, - NS_LITERAL_STRING("enforce")); + u"enforce"_ns); ReportingUtils::Report(window->AsGlobal(), nsGkAtoms::featurePolicyViolation, - NS_LITERAL_STRING("default"), - NS_ConvertUTF8toUTF16(spec), body); + u"default"_ns, NS_ConvertUTF8toUTF16(spec), body); } } // namespace dom diff --git a/dom/security/featurepolicy/test/gtest/TestFeaturePolicyParser.cpp b/dom/security/featurepolicy/test/gtest/TestFeaturePolicyParser.cpp index 0ea882343042..ae6bb6d817f0 100644 --- a/dom/security/featurepolicy/test/gtest/TestFeaturePolicyParser.cpp +++ b/dom/security/featurepolicy/test/gtest/TestFeaturePolicyParser.cpp @@ -14,9 +14,9 @@ using namespace mozilla; using namespace mozilla::dom; -#define URL_SELF NS_LITERAL_CSTRING("https://example.com") -#define URL_EXAMPLE_COM NS_LITERAL_CSTRING("http://example.com") -#define URL_EXAMPLE_NET NS_LITERAL_CSTRING("http://example.net") +#define URL_SELF "https://example.com"_ns +#define URL_EXAMPLE_COM "http://example.com"_ns +#define URL_EXAMPLE_NET "http://example.net"_ns void CheckParser(const nsAString& aInput, bool aExpectedResults, uint32_t aExpectedFeatures, @@ -47,123 +47,116 @@ TEST(FeaturePolicyParser, Basic) CheckParser(EmptyString(), true, 0, parsedFeatures); // Empty string with spaces is still valid. - CheckParser(NS_LITERAL_STRING(" "), true, 0, parsedFeatures); + CheckParser(u" "_ns, true, 0, parsedFeatures); // Non-Existing features with no allowed values - CheckParser(NS_LITERAL_STRING("non-existing-feature"), true, 0, + CheckParser(u"non-existing-feature"_ns, true, 0, parsedFeatures); + CheckParser(u"non-existing-feature;another-feature"_ns, true, 0, parsedFeatures); - CheckParser(NS_LITERAL_STRING("non-existing-feature;another-feature"), true, - 0, parsedFeatures); // Existing feature with no allowed values - CheckParser(NS_LITERAL_STRING("camera"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); // Some spaces. - CheckParser(NS_LITERAL_STRING(" camera "), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u" camera "_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); // A random ; - CheckParser(NS_LITERAL_STRING("camera;"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera;"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); // Another random ; - CheckParser(NS_LITERAL_STRING(";camera;"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u";camera;"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); // 2 features - CheckParser(NS_LITERAL_STRING("camera;microphone"), true, 2, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera;microphone"_ns, true, 2, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); - ASSERT_TRUE(parsedFeatures[1].Name().Equals(NS_LITERAL_STRING("microphone"))); + ASSERT_TRUE(parsedFeatures[1].Name().Equals(u"microphone"_ns)); ASSERT_TRUE(parsedFeatures[1].HasAllowList()); // 2 features with spaces - CheckParser(NS_LITERAL_STRING(" camera ; microphone "), true, 2, - parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u" camera ; microphone "_ns, true, 2, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); - ASSERT_TRUE(parsedFeatures[1].Name().Equals(NS_LITERAL_STRING("microphone"))); + ASSERT_TRUE(parsedFeatures[1].Name().Equals(u"microphone"_ns)); ASSERT_TRUE(parsedFeatures[1].HasAllowList()); // 3 features, but only 2 exist. - CheckParser(NS_LITERAL_STRING("camera;microphone;foobar"), true, 2, - parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera;microphone;foobar"_ns, true, 2, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); - ASSERT_TRUE(parsedFeatures[1].Name().Equals(NS_LITERAL_STRING("microphone"))); + ASSERT_TRUE(parsedFeatures[1].Name().Equals(u"microphone"_ns)); ASSERT_TRUE(parsedFeatures[1].HasAllowList()); // Multiple spaces around the value - CheckParser(NS_LITERAL_STRING("camera 'self'"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'self'"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(selfPrincipal)); // Multiple spaces around the value - CheckParser(NS_LITERAL_STRING("camera 'self' "), true, 1, - parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'self' "_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(selfPrincipal)); // No final ' - CheckParser(NS_LITERAL_STRING("camera 'self"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'self"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].HasAllowList()); ASSERT_TRUE(!parsedFeatures[0].AllowListContains(selfPrincipal)); // Lowercase/Uppercase - CheckParser(NS_LITERAL_STRING("camera 'selF'"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'selF'"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(selfPrincipal)); // Lowercase/Uppercase - CheckParser(NS_LITERAL_STRING("camera * 'self' none' a.com 123"), true, 1, - parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera * 'self' none' a.com 123"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowsAll()); // After a 'none' we don't continue the parsing. - CheckParser(NS_LITERAL_STRING("camera 'none' a.com b.org c.net d.co.uk"), - true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'none' a.com b.org c.net d.co.uk"_ns, true, 1, + parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowsNone()); // After a * we don't continue the parsing. - CheckParser(NS_LITERAL_STRING("camera * a.com b.org c.net d.co.uk"), true, 1, + CheckParser(u"camera * a.com b.org c.net d.co.uk"_ns, true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowsAll()); // 'self' - CheckParser(NS_LITERAL_STRING("camera 'self'"), true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera 'self'"_ns, true, 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(selfPrincipal)); // A couple of URLs - CheckParser(NS_LITERAL_STRING("camera http://example.com http://example.net"), - true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera http://example.com http://example.net"_ns, true, 1, + parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(!parsedFeatures[0].AllowListContains(selfPrincipal)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(exampleComPrincipal)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(exampleNetPrincipal)); // A couple of URLs + self - CheckParser( - NS_LITERAL_STRING("camera http://example.com 'self' http://example.net"), - true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera http://example.com 'self' http://example.net"_ns, true, + 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(selfPrincipal)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(exampleComPrincipal)); ASSERT_TRUE(parsedFeatures[0].AllowListContains(exampleNetPrincipal)); // A couple of URLs but then * - CheckParser(NS_LITERAL_STRING( - "camera http://example.com 'self' http://example.net *"), - true, 1, parsedFeatures); - ASSERT_TRUE(parsedFeatures[0].Name().Equals(NS_LITERAL_STRING("camera"))); + CheckParser(u"camera http://example.com 'self' http://example.net *"_ns, true, + 1, parsedFeatures); + ASSERT_TRUE(parsedFeatures[0].Name().Equals(u"camera"_ns)); ASSERT_TRUE(parsedFeatures[0].AllowsAll()); } diff --git a/dom/security/nsCSPContext.cpp b/dom/security/nsCSPContext.cpp index 62a8f2d5ac48..9ddf51561e7c 100644 --- a/dom/security/nsCSPContext.cpp +++ b/dom/security/nsCSPContext.cpp @@ -661,7 +661,7 @@ nsCSPContext::GetAllowsNavigateTo(nsIURI* aURI, bool aIsFormSubmission, blockedURIForReporting, // aBlockedURI nsCSPContext::BlockedContentSource::eSelf, // aBlockedSource nullptr, // aOriginalURI - NS_LITERAL_STRING("navigate-to"), // aViolatedDirective + u"navigate-to"_ns, // aViolatedDirective i, // aViolatedPolicyIndex EmptyString(), // aObserverSubject NS_ConvertUTF8toUTF16(spec), // aSourceFile @@ -775,13 +775,11 @@ nsCSPContext::LogViolationDetails( } switch (aViolationType) { - CASE_CHECK_AND_REPORT(EVAL, SCRIPT, NS_LITERAL_STRING(""), - CSP_UNSAFE_EVAL, EVAL_VIOLATION_OBSERVER_TOPIC); - CASE_CHECK_AND_REPORT(INLINE_STYLE, STYLESHEET, NS_LITERAL_STRING(""), - CSP_UNSAFE_INLINE, + CASE_CHECK_AND_REPORT(EVAL, SCRIPT, u""_ns, CSP_UNSAFE_EVAL, + EVAL_VIOLATION_OBSERVER_TOPIC); + CASE_CHECK_AND_REPORT(INLINE_STYLE, STYLESHEET, u""_ns, CSP_UNSAFE_INLINE, INLINE_STYLE_VIOLATION_OBSERVER_TOPIC); - CASE_CHECK_AND_REPORT(INLINE_SCRIPT, SCRIPT, NS_LITERAL_STRING(""), - CSP_UNSAFE_INLINE, + CASE_CHECK_AND_REPORT(INLINE_SCRIPT, SCRIPT, u""_ns, CSP_UNSAFE_INLINE, INLINE_SCRIPT_VIOLATION_OBSERVER_TOPIC); CASE_CHECK_AND_REPORT(NONCE_SCRIPT, SCRIPT, aNonce, CSP_UNSAFE_INLINE, SCRIPT_NONCE_VIOLATION_OBSERVER_TOPIC); @@ -1253,14 +1251,13 @@ nsresult nsCSPContext::SendReports( continue; } - rv = uploadChannel->SetUploadStream( - sis, NS_LITERAL_CSTRING("application/csp-report"), -1); + rv = uploadChannel->SetUploadStream(sis, "application/csp-report"_ns, -1); NS_ENSURE_SUCCESS(rv, rv); // if this is an HTTP channel, set the request method to post nsCOMPtr httpChannel(do_QueryInterface(reportChannel)); if (httpChannel) { - rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChannel->SetRequestMethod("POST"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -1334,8 +1331,7 @@ nsresult nsCSPContext::FireViolationEvent( RefPtr event = mozilla::dom::SecurityPolicyViolationEvent::Constructor( - eventTarget, NS_LITERAL_STRING("securitypolicyviolation"), - aViolationEventInit); + eventTarget, u"securitypolicyviolation"_ns, aViolationEventInit); event->SetTrusted(true); ErrorResult rv; @@ -1641,7 +1637,7 @@ nsCSPContext::Permits(Element* aTriggeringElement, // As a hotfix we just allowlist pdf.js internals here explicitly. nsAutoCString uriSpec; aURI->GetSpec(uriSpec); - if (StringBeginsWith(uriSpec, NS_LITERAL_CSTRING("resource://pdf.js/"))) { + if (StringBeginsWith(uriSpec, "resource://pdf.js/"_ns)) { *outPermits = true; return NS_OK; } diff --git a/dom/security/nsCSPParser.cpp b/dom/security/nsCSPParser.cpp index f8c9e0c32df0..abccc5797843 100644 --- a/dom/security/nsCSPParser.cpp +++ b/dom/security/nsCSPParser.cpp @@ -309,7 +309,7 @@ bool nsCSPParser::path(nsCSPHostSrc* aCspHost) { // www.example.com/ should result in www.example.com/ // please note that we do not have to perform any pct-decoding here // because we are just appending a '/' and not any actual chars. - aCspHost->appendPath(NS_LITERAL_STRING("/")); + aCspHost->appendPath(u"/"_ns); return true; } // path can begin with "/" but not "//" @@ -426,7 +426,7 @@ nsCSPBaseSrc* nsCSPParser::keywordSource() { if (!CSP_IsDirective(mCurDir[0], nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE)) { // Todo: Enforce 'strict-dynamic' within default-src; see Bug 1313937 - AutoTArray params = {NS_LITERAL_STRING("strict-dynamic")}; + AutoTArray params = {u"strict-dynamic"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "ignoringStrictDynamic", params); return nullptr; @@ -469,9 +469,8 @@ nsCSPBaseSrc* nsCSPParser::keywordSource() { if (!CSP_IsDirective(mCurDir[0], nsIContentSecurityPolicy::NAVIGATE_TO_DIRECTIVE)) { // Only allow 'unsafe-allow-redirects' within navigate-to. - AutoTArray params = { - NS_LITERAL_STRING("unsafe-allow-redirects"), - NS_LITERAL_STRING("navigate-to")}; + AutoTArray params = {u"unsafe-allow-redirects"_ns, + u"navigate-to"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "IgnoringSourceWithinDirective", params); return nullptr; @@ -646,7 +645,7 @@ nsCSPBaseSrc* nsCSPParser::sourceExpression() { // the default scheme. However, we still would need to apply the default // scheme in case we would parse "*:80". if (mCurToken.EqualsASCII("*")) { - return new nsCSPHostSrc(NS_LITERAL_STRING("*")); + return new nsCSPHostSrc(u"*"_ns); } // Calling resetCurChar allows us to use mCurChar and mEndChar @@ -971,7 +970,7 @@ void nsCSPParser::directive() { // Make sure that the directive-srcs-array contains at least // one directive and one src. if (mCurDir.Length() < 1) { - AutoTArray params = {NS_LITERAL_STRING("directive missing")}; + AutoTArray params = {u"directive missing"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "failedToParseUnrecognizedSource", params); return; @@ -993,8 +992,7 @@ void nsCSPParser::directive() { // by a directive name but does not include any srcs. if (cspDir->equals(nsIContentSecurityPolicy::BLOCK_ALL_MIXED_CONTENT)) { if (mCurDir.Length() > 1) { - AutoTArray params = { - NS_LITERAL_STRING("block-all-mixed-content")}; + AutoTArray params = {u"block-all-mixed-content"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "ignoreSrcForDirective", params); } @@ -1007,8 +1005,7 @@ void nsCSPParser::directive() { // specified by a directive name but does not include any srcs. if (cspDir->equals(nsIContentSecurityPolicy::UPGRADE_IF_INSECURE_DIRECTIVE)) { if (mCurDir.Length() > 1) { - AutoTArray params = { - NS_LITERAL_STRING("upgrade-insecure-requests")}; + AutoTArray params = {u"upgrade-insecure-requests"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "ignoreSrcForDirective", params); } @@ -1075,7 +1072,7 @@ void nsCSPParser::directive() { !srcStr.EqualsASCII(CSP_EnumToUTF8Keyword(CSP_UNSAFE_EVAL)) && !StringBeginsWith( srcStr, nsDependentString(CSP_EnumToUTF16Keyword(CSP_NONCE))) && - !StringBeginsWith(srcStr, NS_LITERAL_STRING("'sha"))) { + !StringBeginsWith(srcStr, u"'sha"_ns)) { AutoTArray params = {srcStr}; logWarningErrorToConsole(nsIScriptError::warningFlag, "ignoringSrcForStrictDynamic", params); @@ -1093,7 +1090,7 @@ void nsCSPParser::directive() { cspDir->equals(nsIContentSecurityPolicy::STYLE_SRC_DIRECTIVE))) { mUnsafeInlineKeywordSrc->invalidate(); // log to the console that unsafe-inline will be ignored - AutoTArray params = {NS_LITERAL_STRING("'unsafe-inline'")}; + AutoTArray params = {u"'unsafe-inline'"_ns}; logWarningErrorToConsole(nsIScriptError::warningFlag, "ignoringSrcWithinScriptStyleSrc", params); } diff --git a/dom/security/nsCSPService.cpp b/dom/security/nsCSPService.cpp index 11b7a7efc967..75be67609218 100644 --- a/dom/security/nsCSPService.cpp +++ b/dom/security/nsCSPService.cpp @@ -79,7 +79,7 @@ bool subjectToCSP(nsIURI* aURI, nsContentPolicyType aContentType) { nsAutoCString uriSpec; aURI->GetSpec(uriSpec); // Exempt pdf.js from being subject to a page's CSP. - if (StringBeginsWith(uriSpec, NS_LITERAL_CSTRING("resource://pdf.js/"))) { + if (StringBeginsWith(uriSpec, "resource://pdf.js/"_ns)) { return false; } if (!isImgOrStyleOrDTD) { diff --git a/dom/security/nsCSPUtils.cpp b/dom/security/nsCSPUtils.cpp index 4cb1158ed985..7c6bd4a4fb99 100644 --- a/dom/security/nsCSPUtils.cpp +++ b/dom/security/nsCSPUtils.cpp @@ -105,8 +105,8 @@ bool CSP_ShouldResponseInheritCSP(nsIChannel* aChannel) { rv = uri->GetSpec(aboutSpec); NS_ENSURE_SUCCESS(rv, false); // also allow about:blank#foo - if (StringBeginsWith(aboutSpec, NS_LITERAL_CSTRING("about:blank")) || - StringBeginsWith(aboutSpec, NS_LITERAL_CSTRING("about:srcdoc"))) { + if (StringBeginsWith(aboutSpec, "about:blank"_ns) || + StringBeginsWith(aboutSpec, "about:srcdoc"_ns)) { return true; } } @@ -1463,7 +1463,7 @@ bool nsCSPPolicy::allows(nsContentPolicyType aContentType, bool nsCSPPolicy::allows(nsContentPolicyType aContentType, enum CSPKeyword aKeyword) const { - return allows(aContentType, aKeyword, NS_LITERAL_STRING(""), false); + return allows(aContentType, aKeyword, u""_ns, false); } void nsCSPPolicy::toString(nsAString& outStr) const { diff --git a/dom/security/nsContentSecurityManager.cpp b/dom/security/nsContentSecurityManager.cpp index a96100ce2a78..03111a8b9cf3 100644 --- a/dom/security/nsContentSecurityManager.cpp +++ b/dom/security/nsContentSecurityManager.cpp @@ -88,7 +88,7 @@ bool nsContentSecurityManager::AllowTopLevelNavigationToDataURI( NS_ENSURE_SUCCESS(rv, true); // Allow data: images as long as they are not SVGs - if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/")) && + if (StringBeginsWith(contentType, "image/"_ns) && !contentType.EqualsLiteral("image/svg+xml")) { return true; } @@ -120,7 +120,7 @@ bool nsContentSecurityManager::AllowTopLevelNavigationToDataURI( AutoTArray params; CopyUTF8toUTF16(NS_UnescapeURL(dataSpec), *params.AppendElement()); nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DATA_URI_BLOCKED"), doc, + "DATA_URI_BLOCKED"_ns, doc, nsContentUtils::eSECURITY_PROPERTIES, "BlockTopLevelDataURINavigation", params); return false; @@ -165,7 +165,7 @@ bool nsContentSecurityManager::AllowInsecureRedirectToDataURI( AutoTArray params; CopyUTF8toUTF16(NS_UnescapeURL(dataSpec), *params.AppendElement()); nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DATA_URI_BLOCKED"), doc, + "DATA_URI_BLOCKED"_ns, doc, nsContentUtils::eSECURITY_PROPERTIES, "BlockSubresourceRedirectToData", params); return false; @@ -218,7 +218,7 @@ nsresult nsContentSecurityManager::CheckFTPSubresourceLoad( CopyUTF8toUTF16(NS_UnescapeURL(spec), *params.AppendElement()); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("FTP_URI_BLOCKED"), doc, + nsIScriptError::warningFlag, "FTP_URI_BLOCKED"_ns, doc, nsContentUtils::eSECURITY_PROPERTIES, "BlockSubresourceFTP", params); return NS_ERROR_CONTENT_BLOCKED; @@ -389,7 +389,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, } case nsIContentPolicy::TYPE_SCRIPT: { - mimeTypeGuess = NS_LITERAL_CSTRING("application/javascript"); + mimeTypeGuess = "application/javascript"_ns; break; } @@ -399,7 +399,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, } case nsIContentPolicy::TYPE_STYLESHEET: { - mimeTypeGuess = NS_LITERAL_CSTRING("text/css"); + mimeTypeGuess = "text/css"_ns; break; } @@ -414,7 +414,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, } case nsIContentPolicy::TYPE_SUBDOCUMENT: { - mimeTypeGuess = NS_LITERAL_CSTRING("text/html"); + mimeTypeGuess = "text/html"_ns; break; } @@ -447,7 +447,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, MOZ_ASSERT(internalContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE, "can not set mime type guess for unexpected internal type"); - mimeTypeGuess = NS_LITERAL_CSTRING(TEXT_EVENT_STREAM); + mimeTypeGuess = nsLiteralCString(TEXT_EVENT_STREAM); } break; } @@ -484,7 +484,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, case nsIContentPolicy::TYPE_MEDIA: { if (internalContentPolicyType == nsIContentPolicy::TYPE_INTERNAL_TRACK) { - mimeTypeGuess = NS_LITERAL_CSTRING("text/vtt"); + mimeTypeGuess = "text/vtt"_ns; } else { mimeTypeGuess = EmptyCString(); } @@ -518,7 +518,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, } case nsIContentPolicy::TYPE_XSLT: { - mimeTypeGuess = NS_LITERAL_CSTRING("application/xml"); + mimeTypeGuess = "application/xml"_ns; #ifdef DEBUG { nsCOMPtr node = aLoadInfo->LoadingNode(); @@ -552,7 +552,7 @@ static nsresult DoContentSecurityChecks(nsIChannel* aChannel, } case nsIContentPolicy::TYPE_WEB_MANIFEST: { - mimeTypeGuess = NS_LITERAL_CSTRING("application/manifest+json"); + mimeTypeGuess = "application/manifest+json"_ns; break; } @@ -707,11 +707,9 @@ static void DebugDoContentSecurityCheck(nsIChannel* aChannel, // Log Principals nsCOMPtr requestPrincipal = aLoadInfo->TriggeringPrincipal(); - LogPrincipal(aLoadInfo->GetLoadingPrincipal(), - NS_LITERAL_STRING("loadingPrincipal")); - LogPrincipal(requestPrincipal, NS_LITERAL_STRING("triggeringPrincipal")); - LogPrincipal(aLoadInfo->PrincipalToInherit(), - NS_LITERAL_STRING("principalToInherit")); + LogPrincipal(aLoadInfo->GetLoadingPrincipal(), u"loadingPrincipal"_ns); + LogPrincipal(requestPrincipal, u"triggeringPrincipal"_ns); + LogPrincipal(aLoadInfo->PrincipalToInherit(), u"principalToInherit"_ns); // Log Redirect Chain MOZ_LOG(sCSMLog, LogLevel::Verbose, (" RedirectChain:\n")); @@ -719,7 +717,7 @@ static void DebugDoContentSecurityCheck(nsIChannel* aChannel, aLoadInfo->RedirectChain()) { nsCOMPtr principal; redirectHistoryEntry->GetPrincipal(getter_AddRefs(principal)); - LogPrincipal(principal, NS_LITERAL_STRING("->")); + LogPrincipal(principal, u"->"_ns); } MOZ_LOG(sCSMLog, LogLevel::Verbose, diff --git a/dom/security/nsContentSecurityUtils.cpp b/dom/security/nsContentSecurityUtils.cpp index 05c8258381cc..f6a62baebc61 100644 --- a/dom/security/nsContentSecurityUtils.cpp +++ b/dom/security/nsContentSecurityUtils.cpp @@ -183,12 +183,9 @@ nsString OptimizeFileName(const nsAString& aFileName) { sCSMLog, LogLevel::Verbose, ("Optimizing FileName: %s", NS_ConvertUTF16toUTF8(optimizedName).get())); - optimizedName.ReplaceSubstring(NS_LITERAL_STRING(".xpi!"), - NS_LITERAL_STRING("!")); - optimizedName.ReplaceSubstring(NS_LITERAL_STRING("shield.mozilla.org!"), - NS_LITERAL_STRING("s!")); - optimizedName.ReplaceSubstring(NS_LITERAL_STRING("mozilla.org!"), - NS_LITERAL_STRING("m!")); + optimizedName.ReplaceSubstring(u".xpi!"_ns, u"!"_ns); + optimizedName.ReplaceSubstring(u"shield.mozilla.org!"_ns, u"s!"_ns); + optimizedName.ReplaceSubstring(u"mozilla.org!"_ns, u"m!"_ns); if (optimizedName.Length() > 80) { optimizedName.Truncate(80); } @@ -238,18 +235,18 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType( static NS_NAMED_LITERAL_STRING(kSingleFileRegex, "^[a-zA-Z0-9.?]+$"); // resource:// and chrome:// - if (StringBeginsWith(fileName, NS_LITERAL_STRING("chrome://"))) { + if (StringBeginsWith(fileName, u"chrome://"_ns)) { return FilenameTypeAndDetails(kChromeURI, Some(fileName)); } - if (StringBeginsWith(fileName, NS_LITERAL_STRING("resource://"))) { + if (StringBeginsWith(fileName, u"resource://"_ns)) { return FilenameTypeAndDetails(kResourceURI, Some(fileName)); } // blob: and data: - if (StringBeginsWith(fileName, NS_LITERAL_STRING("blob:"))) { + if (StringBeginsWith(fileName, u"blob:"_ns)) { return FilenameTypeAndDetails(kBlobUri, Nothing()); } - if (StringBeginsWith(fileName, NS_LITERAL_STRING("data:"))) { + if (StringBeginsWith(fileName, u"data:"_ns)) { return FilenameTypeAndDetails(kDataUri, Nothing()); } @@ -267,10 +264,9 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType( return FilenameTypeAndDetails(kRegexFailure, Nothing()); } if (regexMatch) { - nsCString type = - StringEndsWith(regexResults[2], NS_LITERAL_STRING("mozilla.org.xpi")) - ? kMozillaExtension - : kOtherExtension; + nsCString type = StringEndsWith(regexResults[2], u"mozilla.org.xpi"_ns) + ? kMozillaExtension + : kOtherExtension; auto& extensionNameAndPath = Substring(regexResults[0], ArrayLength("extensions/") - 1); return FilenameTypeAndDetails(type, @@ -309,12 +305,12 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType( if (hr == S_OK && cchDecodedUrl) { nsAutoString sanitizedPathAndScheme; sanitizedPathAndScheme.Append(szOut); - if (sanitizedPathAndScheme == NS_LITERAL_STRING("file")) { - sanitizedPathAndScheme.Append(NS_LITERAL_STRING("://.../")); + if (sanitizedPathAndScheme == u"file"_ns) { + sanitizedPathAndScheme.Append(u"://.../"_ns); sanitizedPathAndScheme.Append(strSanitizedPath); - } else if (sanitizedPathAndScheme == NS_LITERAL_STRING("moz-extension") && + } else if (sanitizedPathAndScheme == u"moz-extension"_ns && collectAdditionalExtensionData) { - sanitizedPathAndScheme.Append(NS_LITERAL_STRING("://[")); + sanitizedPathAndScheme.Append(u"://["_ns); nsCOMPtr uri; nsresult rv = NS_NewURI(getter_AddRefs(uri), fileName); @@ -334,17 +330,15 @@ FilenameTypeAndDetails nsContentSecurityUtils::FilenameToFilenameType( policy->GetId(addOnId); sanitizedPathAndScheme.Append(addOnId); - sanitizedPathAndScheme.Append(NS_LITERAL_STRING(": ")); + sanitizedPathAndScheme.Append(u": "_ns); sanitizedPathAndScheme.Append(policy->Name()); } else { - sanitizedPathAndScheme.Append( - NS_LITERAL_STRING("failed finding addon by host")); + sanitizedPathAndScheme.Append(u"failed finding addon by host"_ns); } } else { - sanitizedPathAndScheme.Append( - NS_LITERAL_STRING("can't get addon off main thread")); + sanitizedPathAndScheme.Append(u"can't get addon off main thread"_ns); } - sanitizedPathAndScheme.Append(NS_LITERAL_STRING("]")); + sanitizedPathAndScheme.Append(u"]"_ns); sanitizedPathAndScheme.Append(url.FilePath()); } return FilenameTypeAndDetails(kSanitizedWindowsURL, @@ -402,24 +396,24 @@ bool nsContentSecurityUtils::IsEvalAllowed(JSContext* cx, // exclusively used in testing contexts. static nsLiteralCString evalAllowlist[] = { // Test-only third-party library - NS_LITERAL_CSTRING("resource://testing-common/sinon-7.2.7.js"), + "resource://testing-common/sinon-7.2.7.js"_ns, // Test-only third-party library - NS_LITERAL_CSTRING("resource://testing-common/ajv-4.1.1.js"), + "resource://testing-common/ajv-4.1.1.js"_ns, // Test-only utility - NS_LITERAL_CSTRING("resource://testing-common/content-task.js"), + "resource://testing-common/content-task.js"_ns, // Tracked by Bug 1584605 - NS_LITERAL_CSTRING("resource:///modules/translation/cld-worker.js"), + "resource:///modules/translation/cld-worker.js"_ns, // require.js implements a script loader for workers. It uses eval // to load the script; but injection is only possible in situations // that you could otherwise control script that gets executed, so // it is okay to allow eval() as it adds no additional attack surface. // Bug 1584564 tracks requiring safe usage of require.js - NS_LITERAL_CSTRING("resource://gre/modules/workers/require.js"), + "resource://gre/modules/workers/require.js"_ns, // The Browser Toolbox/Console - NS_LITERAL_CSTRING("debugger"), + "debugger"_ns, }; // We also permit two specific idioms in eval()-like contexts. We'd like to @@ -515,7 +509,7 @@ bool nsContentSecurityUtils::IsEvalAllowed(JSContext* cx, uint32_t lineNumber = 0, columnNumber = 0; nsJSUtils::GetCallingLocation(cx, fileName, &lineNumber, &columnNumber); if (fileName.IsEmpty()) { - fileName = NS_LITERAL_CSTRING("unknown-file"); + fileName = "unknown-file"_ns; } NS_ConvertUTF8toUTF16 fileNameA(fileName); @@ -595,14 +589,14 @@ void nsContentSecurityUtils::NotifyEvalUsage(bool aIsSystemPrincipal, mozilla::Maybe> extra; if (fileNameTypeAndDetails.second.isSome()) { extra = Some>({EventExtraEntry{ - NS_LITERAL_CSTRING("fileinfo"), + "fileinfo"_ns, NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value())}}); } else { extra = Nothing(); } if (!sTelemetryEventEnabled.exchange(true)) { sTelemetryEventEnabled = true; - Telemetry::SetEventRecordingEnabled(NS_LITERAL_CSTRING("security"), true); + Telemetry::SetEventRecordingEnabled("security"_ns, true); } Telemetry::RecordEvent(eventType, mozilla::Some(fileNameTypeAndDetails.first), extra); @@ -702,12 +696,11 @@ nsresult ParseCSPAndEnforceFrameAncestorCheck( nsAutoCString tCspHeaderValue, tCspROHeaderValue; - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy"), tCspHeaderValue); + Unused << httpChannel->GetResponseHeader("content-security-policy"_ns, + tCspHeaderValue); Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy-report-only"), - tCspROHeaderValue); + "content-security-policy-report-only"_ns, tCspROHeaderValue); // if there are no CSP values, then there is nothing to do here. if (tCspHeaderValue.IsEmpty() && tCspROHeaderValue.IsEmpty()) { @@ -857,17 +850,17 @@ void nsContentSecurityUtils::AssertAboutPageHasCSP(Document* aDocument) { // render without a CSP applied. static nsLiteralCString sAllowedAboutPagesWithNoCSP[] = { // about:blank is a special about page -> no CSP - NS_LITERAL_CSTRING("about:blank"), + "about:blank"_ns, // about:srcdoc is a special about page -> no CSP - NS_LITERAL_CSTRING("about:srcdoc"), + "about:srcdoc"_ns, // about:sync-log displays plain text only -> no CSP - NS_LITERAL_CSTRING("about:sync-log"), + "about:sync-log"_ns, // about:printpreview displays plain text only -> no CSP - NS_LITERAL_CSTRING("about:printpreview"), + "about:printpreview"_ns, // about:logo just displays the firefox logo -> no CSP - NS_LITERAL_CSTRING("about:logo"), + "about:logo"_ns, # if defined(ANDROID) - NS_LITERAL_CSTRING("about:config"), + "about:config"_ns, # endif }; @@ -899,16 +892,16 @@ void nsContentSecurityUtils::AssertAboutPageHasCSP(Document* aDocument) { static nsLiteralCString sLegacyUnsafeInlineAllowList[] = { // Bug 1579160: Remove 'unsafe-inline' from style-src within // about:preferences - NS_LITERAL_CSTRING("about:preferences"), + "about:preferences"_ns, // Bug 1571346: Remove 'unsafe-inline' from style-src within about:addons - NS_LITERAL_CSTRING("about:addons"), + "about:addons"_ns, // Bug 1584485: Remove 'unsafe-inline' from style-src within: // * about:newtab // * about:welcome // * about:home - NS_LITERAL_CSTRING("about:newtab"), - NS_LITERAL_CSTRING("about:welcome"), - NS_LITERAL_CSTRING("about:home"), + "about:newtab"_ns, + "about:welcome"_ns, + "about:home"_ns, }; for (const nsLiteralCString& aUnsafeInlineEntry : @@ -984,23 +977,23 @@ bool nsContentSecurityUtils::ValidateScriptFilename(const char* aFilename, } NS_ConvertUTF8toUTF16 filenameU(aFilename); - if (StringBeginsWith(filenameU, NS_LITERAL_STRING("chrome://"))) { + if (StringBeginsWith(filenameU, u"chrome://"_ns)) { // If it's a chrome:// url, allow it return true; } - if (StringBeginsWith(filenameU, NS_LITERAL_STRING("resource://"))) { + if (StringBeginsWith(filenameU, u"resource://"_ns)) { // If it's a resource:// url, allow it return true; } - if (StringBeginsWith(filenameU, NS_LITERAL_STRING("file://"))) { + if (StringBeginsWith(filenameU, u"file://"_ns)) { // We will temporarily allow all file:// URIs through for now return true; } - if (StringBeginsWith(filenameU, NS_LITERAL_STRING("jar:file://"))) { + if (StringBeginsWith(filenameU, u"jar:file://"_ns)) { // We will temporarily allow all jar URIs through for now return true; } - if (filenameU.Equals(NS_LITERAL_STRING("about:sync-log"))) { + if (filenameU.Equals(u"about:sync-log"_ns)) { // about:sync-log runs in the parent process and displays a directory // listing. The listing has inline javascript that executes on load. return true; @@ -1021,7 +1014,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(const char* aFilename, mozilla::Maybe> extra; if (fileNameTypeAndDetails.second.isSome()) { extra = Some>({EventExtraEntry{ - NS_LITERAL_CSTRING("fileinfo"), + "fileinfo"_ns, NS_ConvertUTF16toUTF8(fileNameTypeAndDetails.second.value())}}); } else { extra = Nothing(); @@ -1029,7 +1022,7 @@ bool nsContentSecurityUtils::ValidateScriptFilename(const char* aFilename, if (!sTelemetryEventEnabled.exchange(true)) { sTelemetryEventEnabled = true; - Telemetry::SetEventRecordingEnabled(NS_LITERAL_CSTRING("security"), true); + Telemetry::SetEventRecordingEnabled("security"_ns, true); } Telemetry::RecordEvent(eventType, mozilla::Some(fileNameTypeAndDetails.first), extra); diff --git a/dom/security/nsHTTPSOnlyUtils.cpp b/dom/security/nsHTTPSOnlyUtils.cpp index f0a46bfbd298..011bc7ea3e86 100644 --- a/dom/security/nsHTTPSOnlyUtils.cpp +++ b/dom/security/nsHTTPSOnlyUtils.cpp @@ -168,7 +168,7 @@ bool nsHTTPSOnlyUtils::OnionException(nsIURI* aURI) { } nsAutoCString host; aURI->GetHost(host); - return StringEndsWith(host, NS_LITERAL_CSTRING(".onion")); + return StringEndsWith(host, ".onion"_ns); } /* static */ diff --git a/dom/security/nsMixedContentBlocker.cpp b/dom/security/nsMixedContentBlocker.cpp index 08b7cb1fc90f..c3f745cc3f54 100644 --- a/dom/security/nsMixedContentBlocker.cpp +++ b/dom/security/nsMixedContentBlocker.cpp @@ -268,7 +268,7 @@ bool nsMixedContentBlocker::IsPotentiallyTrustworthyOnion(nsIURI* aURL) { nsAutoCString host; nsresult rv = aURL->GetHost(host); NS_ENSURE_SUCCESS(rv, false); - return StringEndsWith(host, NS_LITERAL_CSTRING(".onion")); + return StringEndsWith(host, ".onion"_ns); } // static @@ -699,8 +699,7 @@ nsresult nsMixedContentBlocker::ShouldLoad(bool aHadInsecureImageRedirect, EmptyString(), // aScriptSample 0, // aLineNumber 0, // aColumnNumber - nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("blockAllMixedContent"), + nsIScriptError::errorFlag, "blockAllMixedContent"_ns, requestingWindow->Id(), !!aLoadInfo->GetOriginAttributes().mPrivateBrowsingId); *aDecision = REJECT_REQUEST; diff --git a/dom/security/test/gtest/TestFilenameEvalParser.cpp b/dom/security/test/gtest/TestFilenameEvalParser.cpp index eb9e9e11eabe..a127e03457a5 100644 --- a/dom/security/test/gtest/TestFilenameEvalParser.cpp +++ b/dom/security/test/gtest/TestFilenameEvalParser.cpp @@ -94,8 +94,7 @@ TEST(FilenameEvalParser, MozExtension) nsContentSecurityUtils::FilenameToFilenameType(str, false); ASSERT_TRUE(ret.first == kMozillaExtension && ret.second.value() == - NS_LITERAL_STRING( - "federated-learning@s!/experiments/study/api.js")); + u"federated-learning@s!/experiments/study/api.js"_ns); } { // Test mozilla.org replacing NS_NAMED_LITERAL_STRING( @@ -108,8 +107,8 @@ TEST(FilenameEvalParser, MozExtension) ASSERT_TRUE( ret.first == kMozillaExtension && ret.second.value() == - NS_LITERAL_STRING( - "federated-learning@shigeld.m!/experiments/study/api.js")); + nsLiteralString( + u"federated-learning@shigeld.m!/experiments/study/api.js")); } { // Test truncating NS_NAMED_LITERAL_STRING( @@ -119,11 +118,10 @@ TEST(FilenameEvalParser, MozExtension) "study/apiiiiiiiiiiiiiiiiiiiiiiiiiiiiii.js"); FilenameTypeAndDetails ret = nsContentSecurityUtils::FilenameToFilenameType(str, false); - ASSERT_TRUE( - ret.first == kMozillaExtension && - ret.second.value() == - NS_LITERAL_STRING("federated-learning@shigeld.m!/experiments/" - "study/apiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")); + ASSERT_TRUE(ret.first == kMozillaExtension && + ret.second.value() == + u"federated-learning@shigeld.m!/experiments/" + "study/apiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"_ns); } } @@ -191,7 +189,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("gallop")); + ret.second.value() == u"gallop"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -202,7 +200,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("gallop")); + ret.second.value() == u"gallop"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -213,7 +211,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsPath && - ret.second.value() == NS_LITERAL_STRING("content")); + ret.second.value() == u"content"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -224,7 +222,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsPath && - ret.second.value() == NS_LITERAL_STRING("content")); + ret.second.value() == u"content"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -235,7 +233,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsPath && - ret.second.value() == NS_LITERAL_STRING("thing")); + ret.second.value() == u"thing"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -246,7 +244,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("file://.../file.txt")); + ret.second.value() == u"file://.../file.txt"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -257,7 +255,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsPath && - ret.second.value() == NS_LITERAL_STRING("file.txt")); + ret.second.value() == u"file.txt"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -268,7 +266,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("http")); + ret.second.value() == u"http"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -279,7 +277,7 @@ TEST(FilenameEvalParser, Other) nsContentSecurityUtils::FilenameToFilenameType(str, false); #if defined(XP_WIN) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("http")); + ret.second.value() == u"http"_ns); #else ASSERT_TRUE(ret.first == kOther && !ret.second.isSome()); #endif @@ -311,13 +309,12 @@ TEST(FilenameEvalParser, WebExtensionPathParser) mozilla::fallible); nsString& slot = *slotPtr; slot.Truncate(); - slot = NS_LITERAL_STRING("http://example.com"); + slot = u"http://example.com"_ns; - wEI->mName = NS_LITERAL_STRING("gtest Test Extension"); - wEI->mId = NS_LITERAL_STRING("gtesttestextension@mozilla.org"); - wEI->mBaseURL = NS_LITERAL_STRING("file://foo"); - wEI->mMozExtensionHostname = - NS_LITERAL_CSTRING("e37c3c08-beac-a04b-8032-c4f699a1a856"); + wEI->mName = u"gtest Test Extension"_ns; + wEI->mId = u"gtesttestextension@mozilla.org"_ns; + wEI->mBaseURL = u"file://foo"_ns; + wEI->mMozExtensionHostname = "e37c3c08-beac-a04b-8032-c4f699a1a856"_ns; mozilla::ErrorResult eR; RefPtr w = @@ -332,9 +329,8 @@ TEST(FilenameEvalParser, WebExtensionPathParser) ASSERT_TRUE(ret.first == kSanitizedWindowsURL && ret.second.value() == - NS_LITERAL_STRING( - "moz-extension://[gtesttestextension@mozilla.org: " - "gtest Test Extension]/path/to/file.js")); + u"moz-extension://[gtesttestextension@mozilla.org: " + "gtest Test Extension]/path/to/file.js"_ns); w->SetActive(false, eR); } @@ -345,7 +341,7 @@ TEST(FilenameEvalParser, WebExtensionPathParser) FilenameTypeAndDetails ret = nsContentSecurityUtils::FilenameToFilenameType(str, false); ASSERT_TRUE(ret.first == kSanitizedWindowsURL && - ret.second.value() == NS_LITERAL_STRING("moz-extension")); + ret.second.value() == u"moz-extension"_ns); } { NS_NAMED_LITERAL_STRING( @@ -355,8 +351,8 @@ TEST(FilenameEvalParser, WebExtensionPathParser) ASSERT_TRUE( ret.first == kSanitizedWindowsURL && ret.second.value() == - NS_LITERAL_STRING( - "moz-extension://[failed finding addon by host]/file.js")); + nsLiteralString( + u"moz-extension://[failed finding addon by host]/file.js")); } { NS_NAMED_LITERAL_STRING( @@ -367,8 +363,8 @@ TEST(FilenameEvalParser, WebExtensionPathParser) nsContentSecurityUtils::FilenameToFilenameType(str, true); ASSERT_TRUE(ret.first == kSanitizedWindowsURL && ret.second.value() == - NS_LITERAL_STRING("moz-extension://[failed finding addon " - "by host]/path/to/file.js")); + u"moz-extension://[failed finding addon " + "by host]/path/to/file.js"_ns); } } #endif diff --git a/dom/serviceworkers/FetchEventOpChild.cpp b/dom/serviceworkers/FetchEventOpChild.cpp index f81da0b18f97..88735dc84218 100644 --- a/dom/serviceworkers/FetchEventOpChild.cpp +++ b/dom/serviceworkers/FetchEventOpChild.cpp @@ -94,8 +94,7 @@ void AsyncLog(nsIInterceptedChannel* aChannel, const nsACString& aScriptSpec, const nsTArray params = std::move(aParams); reporter->AddConsoleReport( - nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Service Worker Interception"), + nsIScriptError::errorFlag, "Service Worker Interception"_ns, nsContentUtils::eDOM_PROPERTIES, aScriptSpec, aLineNumber, aColumnNumber, aMessageName, params); } @@ -129,7 +128,7 @@ class SynthesizeResponseWatcher final : public nsIInterceptedBodyCallback { AsyncLog(mInterceptedChannel, mClosure.respondWithScriptSpec(), mClosure.respondWithLineNumber(), mClosure.respondWithColumnNumber(), - NS_LITERAL_CSTRING("InterceptionFailedWithURL"), {mRequestURL}); + "InterceptionFailedWithURL"_ns, {mRequestURL}); CancelInterception(NS_ERROR_INTERCEPTION_FAILED); diff --git a/dom/serviceworkers/ServiceWorker.cpp b/dom/serviceworkers/ServiceWorker.cpp index 667fa8e0e31d..8d067de100c1 100644 --- a/dom/serviceworkers/ServiceWorker.cpp +++ b/dom/serviceworkers/ServiceWorker.cpp @@ -82,7 +82,7 @@ ServiceWorker::ServiceWorker(nsIGlobalObject* aGlobal, MOZ_DIAGNOSTIC_ASSERT(aGlobal); MOZ_DIAGNOSTIC_ASSERT(mInner); - KeepAliveIfHasListenersFor(NS_LITERAL_STRING("statechange")); + KeepAliveIfHasListenersFor(u"statechange"_ns); // The error event handler is required by the spec currently, but is not used // anywhere. Don't keep the object alive in that case. @@ -153,13 +153,13 @@ void ServiceWorker::MaybeDispatchStateChangeEvent() { } mLastNotifiedState = mDescriptor.State(); - DOMEventTargetHelper::DispatchTrustedEvent(NS_LITERAL_STRING("statechange")); + DOMEventTargetHelper::DispatchTrustedEvent(u"statechange"_ns); // Once we have transitioned to the redundant state then no // more statechange events will occur. We can allow the DOM // object to GC if script is not holding it alive. if (mLastNotifiedState == ServiceWorkerState::Redundant) { - IgnoreKeepAliveIfHasListenersFor(NS_LITERAL_STRING("statechange")); + IgnoreKeepAliveIfHasListenersFor(u"statechange"_ns); } } diff --git a/dom/serviceworkers/ServiceWorkerContainer.cpp b/dom/serviceworkers/ServiceWorkerContainer.cpp index 07d2236296ee..ad9e6ff7ddef 100644 --- a/dom/serviceworkers/ServiceWorkerContainer.cpp +++ b/dom/serviceworkers/ServiceWorkerContainer.cpp @@ -155,7 +155,7 @@ void ServiceWorkerContainer::ControllerChanged(ErrorResult& aRv) { return; } mControllerWorker = go->GetOrCreateServiceWorker(go->GetController().ref()); - aRv = DispatchTrustedEvent(NS_LITERAL_STRING("controllerchange")); + aRv = DispatchTrustedEvent(u"controllerchange"_ns); } using mozilla::dom::ipc::StructuredCloneData; @@ -356,8 +356,7 @@ already_AddRefed ServiceWorkerContainer::Register( // Check content policy. int16_t decision = nsIContentPolicy::ACCEPT; rv = NS_CheckContentLoadPolicy(scriptURI, secCheckLoadInfo, - NS_LITERAL_CSTRING("application/javascript"), - &decision); + "application/javascript"_ns, &decision); if (NS_FAILED(rv)) { aRv.Throw(NS_ERROR_DOM_SECURITY_ERR); return nullptr; @@ -388,7 +387,7 @@ already_AddRefed ServiceWorkerContainer::Register( AutoTArray param; CopyUTF8toUTF16(cleanedScopeURL, *param.AppendElement()); nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Service Workers"), aDoc, + "Service Workers"_ns, aDoc, nsContentUtils::eDOM_PROPERTIES, "ServiceWorkerRegisterStorageError", param); }); @@ -431,7 +430,7 @@ already_AddRefed ServiceWorkerContainer::GetRegistrations( ErrorResult& aRv) { nsIGlobalObject* global = GetGlobalIfValid(aRv, [](Document* aDoc) { nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Service Workers"), aDoc, + "Service Workers"_ns, aDoc, nsContentUtils::eDOM_PROPERTIES, "ServiceWorkerGetRegistrationStorageError"); }); @@ -490,7 +489,7 @@ already_AddRefed ServiceWorkerContainer::GetRegistration( const nsAString& aURL, ErrorResult& aRv) { nsIGlobalObject* global = GetGlobalIfValid(aRv, [](Document* aDoc) { nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Service Workers"), aDoc, + "Service Workers"_ns, aDoc, nsContentUtils::eDOM_PROPERTIES, "ServiceWorkerGetRegistrationStorageError"); }); @@ -729,10 +728,7 @@ void ServiceWorkerContainer::DispatchMessage(RefPtr aMessage) { } RefPtr event = MessageEvent::Constructor( - this, - deserializationFailed ? NS_LITERAL_STRING("messageerror") - : NS_LITERAL_STRING("message"), - init); + this, deserializationFailed ? u"messageerror"_ns : u"message"_ns, init); event->SetTrusted(true); result = NS_OK; diff --git a/dom/serviceworkers/ServiceWorkerEvents.cpp b/dom/serviceworkers/ServiceWorkerEvents.cpp index 63ea17fe2ae4..070cf4a2d593 100644 --- a/dom/serviceworkers/ServiceWorkerEvents.cpp +++ b/dom/serviceworkers/ServiceWorkerEvents.cpp @@ -61,12 +61,11 @@ void AsyncLog(nsIInterceptedChannel* aInterceptedChannel, nsCOMPtr reporter = aInterceptedChannel->GetConsoleReportCollector(); if (reporter) { - reporter->AddConsoleReport( - nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("Service Worker Interception"), - nsContentUtils::eDOM_PROPERTIES, aRespondWithScriptSpec, - aRespondWithLineNumber, aRespondWithColumnNumber, aMessageName, - aParams); + reporter->AddConsoleReport(nsIScriptError::errorFlag, + "Service Worker Interception"_ns, + nsContentUtils::eDOM_PROPERTIES, + aRespondWithScriptSpec, aRespondWithLineNumber, + aRespondWithColumnNumber, aMessageName, aParams); } } @@ -226,8 +225,7 @@ class BodyCopyHandle final : public nsIInterceptedBodyCallback { AsyncLog(mClosure->mInterceptedChannel, mClosure->mRespondWithScriptSpec, mClosure->mRespondWithLineNumber, mClosure->mRespondWithColumnNumber, - NS_LITERAL_CSTRING("InterceptionFailedWithURL"), - mClosure->mRequestURL); + "InterceptionFailedWithURL"_ns, mClosure->mRequestURL); event = new CancelChannelRunnable(mClosure->mInterceptedChannel, mClosure->mRegistration, NS_ERROR_INTERCEPTION_FAILED); @@ -454,7 +452,7 @@ class RespondWithHandler final : public PromiseNativeHandler { if (!mRequestWasHandled) { ::AsyncLog(mInterceptedChannel, mRespondWithScriptSpec, mRespondWithLineNumber, mRespondWithColumnNumber, - NS_LITERAL_CSTRING("InterceptionFailedWithURL"), mRequestURL); + "InterceptionFailedWithURL"_ns, mRequestURL); CancelRequest(NS_ERROR_INTERCEPTION_FAILED); } } @@ -473,7 +471,7 @@ class MOZ_STACK_CLASS AutoCancel { : mOwner(aOwner), mLine(0), mColumn(0), - mMessageName(NS_LITERAL_CSTRING("InterceptionFailedWithURL")) { + mMessageName("InterceptionFailedWithURL"_ns) { mParams.AppendElement(aRequestURL); } @@ -574,10 +572,9 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column, valueString); - autoCancel.SetCancelMessageAndLocation( - sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), mRequestURL, - valueString); + autoCancel.SetCancelMessageAndLocation(sourceSpec, line, column, + "InterceptedNonResponseWithURL"_ns, + mRequestURL, valueString); return; } @@ -591,10 +588,9 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column, valueString); - autoCancel.SetCancelMessageAndLocation( - sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), mRequestURL, - valueString); + autoCancel.SetCancelMessageAndLocation(sourceSpec, line, column, + "InterceptedNonResponseWithURL"_ns, + mRequestURL, valueString); return; } @@ -612,8 +608,8 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, // has more than one item. if (response->Type() == ResponseType::Error) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("InterceptedErrorResponseWithURL"), mRequestURL); + autoCancel.SetCancelMessage("InterceptedErrorResponseWithURL"_ns, + mRequestURL); return; } @@ -625,24 +621,22 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, NS_ConvertASCIItoUTF16 modeString( RequestModeValues::GetString(mRequestMode)); - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadOpaqueInterceptionRequestModeWithURL"), - mRequestURL, modeString); + autoCancel.SetCancelMessage("BadOpaqueInterceptionRequestModeWithURL"_ns, + mRequestURL, modeString); return; } if (mRequestRedirectMode != RequestRedirect::Manual && response->Type() == ResponseType::Opaqueredirect) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadOpaqueRedirectInterceptionWithURL"), - mRequestURL); + autoCancel.SetCancelMessage("BadOpaqueRedirectInterceptionWithURL"_ns, + mRequestURL); return; } if (mRequestRedirectMode != RequestRedirect::Follow && response->Redirected()) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadRedirectModeInterceptionWithURL"), mRequestURL); + autoCancel.SetCancelMessage("BadRedirectModeInterceptionWithURL"_ns, + mRequestURL); return; } @@ -655,8 +649,8 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, return; } if (NS_WARN_IF(bodyUsed)) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("InterceptedUsedResponseWithURL"), mRequestURL); + autoCancel.SetCancelMessage("InterceptedUsedResponseWithURL"_ns, + mRequestURL); return; } } @@ -685,9 +679,8 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, // The variadic template provided by StringArrayAppender requires exactly // an nsString. NS_ConvertUTF8toUTF16 responseURL(ir->GetUnfilteredURL()); - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("CorsResponseForSameOriginRequest"), mRequestURL, - responseURL); + autoCancel.SetCancelMessage("CorsResponseForSameOriginRequest"_ns, + mRequestURL, responseURL); return; } @@ -706,7 +699,7 @@ void RespondWithHandler::ResolvedCallback(JSContext* aCx, // fragment and avoid overriding in that case. if (!mRequestFragment.IsEmpty() && !responseURL.IsEmpty()) { MOZ_ASSERT(!responseURL.Contains('#')); - responseURL.Append(NS_LITERAL_CSTRING("#")); + responseURL.Append("#"_ns); responseURL.Append(mRequestFragment); } } @@ -752,8 +745,8 @@ void RespondWithHandler::RejectedCallback(JSContext* aCx, valueString); ::AsyncLog(mInterceptedChannel, sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptionRejectedResponseWithURL"), - mRequestURL, valueString); + "InterceptionRejectedResponseWithURL"_ns, mRequestURL, + valueString); CancelRequest(NS_ERROR_INTERCEPTION_FAILED); } @@ -850,7 +843,7 @@ void FetchEvent::ReportCanceled() { if (mChannel) { ::AsyncLog(mChannel.get(), mPreventDefaultScriptSpec, mPreventDefaultLineNumber, mPreventDefaultColumnNumber, - NS_LITERAL_CSTRING("InterceptionCanceledWithURL"), requestURL); + "InterceptionCanceledWithURL"_ns, requestURL); } else { mRespondWithHandler->ReportCanceled(mPreventDefaultScriptSpec, mPreventDefaultLineNumber, diff --git a/dom/serviceworkers/ServiceWorkerManager.cpp b/dom/serviceworkers/ServiceWorkerManager.cpp index ac67e977a78c..ee74595c757e 100644 --- a/dom/serviceworkers/ServiceWorkerManager.cpp +++ b/dom/serviceworkers/ServiceWorkerManager.cpp @@ -2898,7 +2898,7 @@ ServiceWorkerManager::RegisterForAddonPrincipal(nsIPrincipal* aPrincipal, } nsCString scope; - auto result = addonPolicy->GetURL(NS_LITERAL_STRING("")); + auto result = addonPolicy->GetURL(u""_ns); if (result.isOk()) { scope.Assign(NS_ConvertUTF16toUTF8(result.unwrap())); } else { diff --git a/dom/serviceworkers/ServiceWorkerManager.h b/dom/serviceworkers/ServiceWorkerManager.h index 294548a0635a..f8b9b1dd19ba 100644 --- a/dom/serviceworkers/ServiceWorkerManager.h +++ b/dom/serviceworkers/ServiceWorkerManager.h @@ -222,7 +222,7 @@ class ServiceWorkerManager final : public nsIServiceWorkerManager, * so that argument might look like: nsTArray { some_nsString, * PromiseFlatString(some_nsSubString_aka_nsAString), * NS_ConvertUTF8toUTF16(some_nsCString_or_nsCSubString), - * NS_LITERAL_STRING("some literal") }. If you have anything else, like a + * u"some literal"_ns }. If you have anything else, like a * number, you can use an nsAutoString with AppendInt/friends. * * @param [aFlags] diff --git a/dom/serviceworkers/ServiceWorkerOp.cpp b/dom/serviceworkers/ServiceWorkerOp.cpp index 7ae6e3f231a4..8a04baa08723 100644 --- a/dom/serviceworkers/ServiceWorkerOp.cpp +++ b/dom/serviceworkers/ServiceWorkerOp.cpp @@ -664,8 +664,8 @@ class PushEventOp final : public ExtendableEventOp { pushEventInit.mCancelable = false; GlobalObject globalObj(aCx, aWorkerPrivate->GlobalScope()->GetWrapper()); - RefPtr pushEvent = PushEvent::Constructor( - globalObj, NS_LITERAL_STRING("push"), pushEventInit, result); + RefPtr pushEvent = + PushEvent::Constructor(globalObj, u"push"_ns, pushEventInit, result); if (NS_WARN_IF(result.Failed())) { return false; @@ -754,7 +754,7 @@ class PushSubscriptionChangeEventOp final : public ExtendableEventOp { init.mCancelable = false; RefPtr event = ExtendableEvent::Constructor( - target, NS_LITERAL_STRING("pushsubscriptionchange"), init); + target, u"pushsubscriptionchange"_ns, init); event->SetTrusted(true); nsresult rv = DispatchExtendableEventOnWorkerScope( @@ -984,9 +984,7 @@ class MessageEventOp final : public ExtendableEventOp { RefPtr target = aWorkerPrivate->GlobalScope(); RefPtr extendableEvent = ExtendableMessageEvent::Constructor( - target, - deserializationFailed ? NS_LITERAL_STRING("messageerror") - : NS_LITERAL_STRING("message"), + target, deserializationFailed ? u"messageerror"_ns : u"message"_ns, init); extendableEvent->SetTrusted(true); @@ -1015,7 +1013,7 @@ class MOZ_STACK_CLASS FetchEventOp::AutoCancel { : mOwner(aOwner), mLine(0), mColumn(0), - mMessageName(NS_LITERAL_CSTRING("InterceptionFailedWithURL")) { + mMessageName("InterceptionFailedWithURL"_ns) { MOZ_ASSERT(IsCurrentThreadRunningWorker()); MOZ_ASSERT(mOwner); @@ -1160,8 +1158,7 @@ void FetchEventOp::ReportCanceled(const nsCString& aPreventDefaultScriptSpec, GetRequestURL(requestURL); AsyncLog(aPreventDefaultScriptSpec, aPreventDefaultLineNumber, - aPreventDefaultColumnNumber, - NS_LITERAL_CSTRING("InterceptionCanceledWithURL"), + aPreventDefaultColumnNumber, "InterceptionCanceledWithURL"_ns, {std::move(requestURL)}); } @@ -1305,10 +1302,9 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column, valueString); - autoCancel.SetCancelMessageAndLocation( - sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), requestURL, - valueString); + autoCancel.SetCancelMessageAndLocation(sourceSpec, line, column, + "InterceptedNonResponseWithURL"_ns, + requestURL, valueString); return; } @@ -1322,10 +1318,9 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, nsContentUtils::ExtractErrorValues(aCx, aValue, sourceSpec, &line, &column, valueString); - autoCancel.SetCancelMessageAndLocation( - sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptedNonResponseWithURL"), requestURL, - valueString); + autoCancel.SetCancelMessageAndLocation(sourceSpec, line, column, + "InterceptedNonResponseWithURL"_ns, + requestURL, valueString); return; } @@ -1343,8 +1338,8 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, // has more than one item. if (response->Type() == ResponseType::Error) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("InterceptedErrorResponseWithURL"), requestURL); + autoCancel.SetCancelMessage("InterceptedErrorResponseWithURL"_ns, + requestURL); return; } @@ -1360,9 +1355,8 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, nsAutoString requestURL; GetRequestURL(requestURL); - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadOpaqueInterceptionRequestModeWithURL"), - requestURL, modeString); + autoCancel.SetCancelMessage("BadOpaqueInterceptionRequestModeWithURL"_ns, + requestURL, modeString); return; } @@ -1371,15 +1365,15 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, if (requestRedirectMode != RequestRedirect::Manual && response->Type() == ResponseType::Opaqueredirect) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadOpaqueRedirectInterceptionWithURL"), requestURL); + autoCancel.SetCancelMessage("BadOpaqueRedirectInterceptionWithURL"_ns, + requestURL); return; } if (requestRedirectMode != RequestRedirect::Follow && response->Redirected()) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("BadRedirectModeInterceptionWithURL"), requestURL); + autoCancel.SetCancelMessage("BadRedirectModeInterceptionWithURL"_ns, + requestURL); return; } @@ -1392,8 +1386,8 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, return; } if (NS_WARN_IF(bodyUsed)) { - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("InterceptedUsedResponseWithURL"), requestURL); + autoCancel.SetCancelMessage("InterceptedUsedResponseWithURL"_ns, + requestURL); return; } } @@ -1422,9 +1416,8 @@ void FetchEventOp::ResolvedCallback(JSContext* aCx, // The variadic template provided by StringArrayAppender requires exactly // an nsString. NS_ConvertUTF8toUTF16 responseURL(ir->GetUnfilteredURL()); - autoCancel.SetCancelMessage( - NS_LITERAL_CSTRING("CorsResponseForSameOriginRequest"), requestURL, - responseURL); + autoCancel.SetCancelMessage("CorsResponseForSameOriginRequest"_ns, + requestURL, responseURL); return; } @@ -1474,8 +1467,7 @@ void FetchEventOp::RejectedCallback(JSContext* aCx, nsString requestURL; GetRequestURL(requestURL); - AsyncLog(sourceSpec, line, column, - NS_LITERAL_CSTRING("InterceptionRejectedResponseWithURL"), + AsyncLog(sourceSpec, line, column, "InterceptionRejectedResponseWithURL"_ns, {std::move(requestURL), valueString}); mRespondWithPromiseHolder.Resolve( @@ -1558,8 +1550,8 @@ nsresult FetchEventOp::DispatchFetchEvent(JSContext* aCx, /** * Step 4b: create the FetchEvent */ - RefPtr fetchEvent = FetchEvent::Constructor( - globalObject, NS_LITERAL_STRING("fetch"), fetchEventInit); + RefPtr fetchEvent = + FetchEvent::Constructor(globalObject, u"fetch"_ns, fetchEventInit); fetchEvent->SetTrusted(true); fetchEvent->PostInit(args.workerScriptSpec(), this); diff --git a/dom/serviceworkers/ServiceWorkerPrivate.cpp b/dom/serviceworkers/ServiceWorkerPrivate.cpp index 2e4ad89f5a51..7ccf603f7ca0 100644 --- a/dom/serviceworkers/ServiceWorkerPrivate.cpp +++ b/dom/serviceworkers/ServiceWorkerPrivate.cpp @@ -504,9 +504,7 @@ class SendMessageEventRunnable final : public ExtendableEventWorkerRunnable { RefPtr target = aWorkerPrivate->GlobalScope(); RefPtr extendableEvent = ExtendableMessageEvent::Constructor( - target, - deserializationFailed ? NS_LITERAL_STRING("messageerror") - : NS_LITERAL_STRING("message"), + target, deserializationFailed ? u"messageerror"_ns : u"message"_ns, init); extendableEvent->SetTrusted(true); @@ -844,8 +842,8 @@ class SendPushEventRunnable final pei.mCancelable = false; ErrorResult result; - RefPtr event = PushEvent::Constructor( - globalObj, NS_LITERAL_STRING("push"), pei, result); + RefPtr event = + PushEvent::Constructor(globalObj, u"push"_ns, pei, result); if (NS_WARN_IF(result.Failed())) { result.SuppressException(); errorReporter->Report(); @@ -885,7 +883,7 @@ class SendPushSubscriptionChangeEventRunnable final init.mCancelable = false; RefPtr event = ExtendableEvent::Constructor( - target, NS_LITERAL_STRING("pushsubscriptionchange"), init); + target, u"pushsubscriptionchange"_ns, init); event->SetTrusted(true); @@ -1480,7 +1478,7 @@ class FetchEventRunnable : public ExtendableFunctionalEventWorkerRunnable, } RefPtr event = - FetchEvent::Constructor(globalObj, NS_LITERAL_STRING("fetch"), init); + FetchEvent::Constructor(globalObj, u"fetch"_ns, init); event->PostInit(mInterceptedChannel, mRegistration, mScriptSpec); event->SetTrusted(true); diff --git a/dom/serviceworkers/ServiceWorkerRegistrar.cpp b/dom/serviceworkers/ServiceWorkerRegistrar.cpp index 341306834dfc..4d8bf8c6b81c 100644 --- a/dom/serviceworkers/ServiceWorkerRegistrar.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistrar.cpp @@ -1190,7 +1190,7 @@ ServiceWorkerRegistrar::BlockShutdown(nsIAsyncShutdownClient* aClient) { NS_IMETHODIMP ServiceWorkerRegistrar::GetName(nsAString& aName) { - aName = NS_LITERAL_STRING("ServiceWorkerRegistrar: Flushing data"); + aName = u"ServiceWorkerRegistrar: Flushing data"_ns; return NS_OK; } @@ -1199,11 +1199,10 @@ ServiceWorkerRegistrar::GetState(nsIPropertyBag** aBagOut) { nsCOMPtr propertyBag = do_CreateInstance("@mozilla.org/hash-property-bag;1"); - MOZ_TRY(propertyBag->SetPropertyAsBool(NS_LITERAL_STRING("shuttingDown"), - mShuttingDown)); + MOZ_TRY(propertyBag->SetPropertyAsBool(u"shuttingDown"_ns, mShuttingDown)); - MOZ_TRY(propertyBag->SetPropertyAsBool( - NS_LITERAL_STRING("saveDataRunnableDispatched"), mRunnableDispatched)); + MOZ_TRY(propertyBag->SetPropertyAsBool(u"saveDataRunnableDispatched"_ns, + mRunnableDispatched)); propertyBag.forget(aBagOut); diff --git a/dom/serviceworkers/ServiceWorkerRegistration.cpp b/dom/serviceworkers/ServiceWorkerRegistration.cpp index e8d84b80d36a..acbc353e204d 100644 --- a/dom/serviceworkers/ServiceWorkerRegistration.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistration.cpp @@ -48,7 +48,7 @@ ServiceWorkerRegistration::ServiceWorkerRegistration( mDispatchedUpdateFoundId(kInvalidUpdateFoundId) { MOZ_DIAGNOSTIC_ASSERT(mInner); - KeepAliveIfHasListenersFor(NS_LITERAL_STRING("updatefound")); + KeepAliveIfHasListenersFor(u"updatefound"_ns); mInner->SetServiceWorkerRegistration(this); } @@ -133,7 +133,7 @@ void ServiceWorkerRegistration::RegistrationCleared() { // Our underlying registration was removed from SWM, so we // will never get an updatefound event again. We can let // the object GC if content is not holding it alive. - IgnoreKeepAliveIfHasListenersFor(NS_LITERAL_STRING("updatefound")); + IgnoreKeepAliveIfHasListenersFor(u"updatefound"_ns); } already_AddRefed ServiceWorkerRegistration::GetInstalling() @@ -445,7 +445,7 @@ void ServiceWorkerRegistration::MaybeDispatchUpdateFound() { } mDispatchedUpdateFoundId = scheduledId; - DispatchTrustedEvent(NS_LITERAL_STRING("updatefound")); + DispatchTrustedEvent(u"updatefound"_ns); } void ServiceWorkerRegistration::UpdateStateInternal( diff --git a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp index d3dfe206bda3..a06de716a410 100644 --- a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp +++ b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp @@ -347,8 +347,7 @@ void ServiceWorkerRegistrationInfo::Activate() { ServiceWorkerPrivate* workerPrivate = mActiveWorker->WorkerPrivate(); MOZ_ASSERT(workerPrivate); - nsresult rv = workerPrivate->SendLifeCycleEvent(NS_LITERAL_STRING("activate"), - callback); + nsresult rv = workerPrivate->SendLifeCycleEvent(u"activate"_ns, callback); if (NS_WARN_IF(NS_FAILED(rv))) { nsCOMPtr failRunnable = NewRunnableMethod( "dom::ServiceWorkerRegistrationInfo::FinishActivate", this, diff --git a/dom/serviceworkers/ServiceWorkerScriptCache.cpp b/dom/serviceworkers/ServiceWorkerScriptCache.cpp index 935a3cb49d09..c998a23382bc 100644 --- a/dom/serviceworkers/ServiceWorkerScriptCache.cpp +++ b/dom/serviceworkers/ServiceWorkerScriptCache.cpp @@ -542,8 +542,7 @@ class CompareManager final : public PromiseNativeHandler { return rv; } - RefPtr ir = - new InternalResponse(200, NS_LITERAL_CSTRING("OK")); + RefPtr ir = new InternalResponse(200, "OK"_ns); ir->SetBody(body, aCN->Buffer().Length()); ir->SetURLList(aCN->URLList()); @@ -684,8 +683,7 @@ nsresult CompareNetwork::Initialize(nsIPrincipal* aPrincipal, MOZ_ASSERT(NS_SUCCEEDED(rv)); } - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Service-Worker"), - NS_LITERAL_CSTRING("script"), + rv = httpChannel->SetRequestHeader("Service-Worker"_ns, "script"_ns, /* merge */ false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -917,9 +915,8 @@ CompareNetwork::OnStreamComplete(nsIStreamLoader* aLoader, // in aStatus and they never reach this point. char16_t* buffer = nullptr; size_t len = 0; - rv = ScriptLoader::ConvertToUTF16(channel, aString, aLen, - NS_LITERAL_STRING("UTF-8"), nullptr, - buffer, len); + rv = ScriptLoader::ConvertToUTF16(channel, aString, aLen, u"UTF-8"_ns, + nullptr, buffer, len); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -959,8 +956,8 @@ CompareNetwork::OnStreamComplete(nsIStreamLoader* aLoader, // Note: we explicitly don't check for the return value here, because the // absence of the header is not an error condition. - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Service-Worker-Allowed"), mMaxScope); + Unused << httpChannel->GetResponseHeader("Service-Worker-Allowed"_ns, + mMaxScope); // [9.2 Update]4.13, If response's cache state is not "local", // set registration's last update check time to the current time @@ -1009,9 +1006,8 @@ CompareNetwork::OnStreamComplete(nsIStreamLoader* aLoader, char16_t* buffer = nullptr; size_t len = 0; - rv = ScriptLoader::ConvertToUTF16(httpChannel, aString, aLen, - NS_LITERAL_STRING("UTF-8"), nullptr, buffer, - len); + rv = ScriptLoader::ConvertToUTF16(httpChannel, aString, aLen, u"UTF-8"_ns, + nullptr, buffer, len); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1089,8 +1085,8 @@ CompareCache::OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aContext, char16_t* buffer = nullptr; size_t len = 0; - nsresult rv = ScriptLoader::ConvertToUTF16( - nullptr, aString, aLen, NS_LITERAL_STRING("UTF-8"), nullptr, buffer, len); + nsresult rv = ScriptLoader::ConvertToUTF16(nullptr, aString, aLen, + u"UTF-8"_ns, nullptr, buffer, len); if (NS_WARN_IF(NS_FAILED(rv))) { Finish(rv, false); return rv; diff --git a/dom/serviceworkers/ServiceWorkerShutdownBlocker.cpp b/dom/serviceworkers/ServiceWorkerShutdownBlocker.cpp index 5e8bb3ad9ffe..844ee35d9ff7 100644 --- a/dom/serviceworkers/ServiceWorkerShutdownBlocker.cpp +++ b/dom/serviceworkers/ServiceWorkerShutdownBlocker.cpp @@ -24,8 +24,8 @@ namespace dom { NS_IMPL_ISUPPORTS(ServiceWorkerShutdownBlocker, nsIAsyncShutdownBlocker) NS_IMETHODIMP ServiceWorkerShutdownBlocker::GetName(nsAString& aNameOut) { - aNameOut = NS_LITERAL_STRING( - "ServiceWorkerShutdownBlocker: shutting down Service Workers"); + aNameOut = nsLiteralString( + u"ServiceWorkerShutdownBlocker: shutting down Service Workers"); return NS_OK; } @@ -53,14 +53,14 @@ NS_IMETHODIMP ServiceWorkerShutdownBlocker::GetState(nsIPropertyBag** aBagOut) { return NS_ERROR_OUT_OF_MEMORY; } - nsresult rv = propertyBag->SetPropertyAsBool( - NS_LITERAL_STRING("acceptingPromises"), IsAcceptingPromises()); + nsresult rv = propertyBag->SetPropertyAsBool(u"acceptingPromises"_ns, + IsAcceptingPromises()); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - rv = propertyBag->SetPropertyAsUint32(NS_LITERAL_STRING("pendingPromises"), + rv = propertyBag->SetPropertyAsUint32(u"pendingPromises"_ns, GetPendingPromises()); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -74,8 +74,7 @@ NS_IMETHODIMP ServiceWorkerShutdownBlocker::GetState(nsIPropertyBag** aBagOut) { shutdownStates.Append(", "); } - rv = propertyBag->SetPropertyAsACString(NS_LITERAL_STRING("shutdownStates"), - shutdownStates); + rv = propertyBag->SetPropertyAsACString(u"shutdownStates"_ns, shutdownStates); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; @@ -95,9 +94,9 @@ ServiceWorkerShutdownBlocker::CreateAndRegisterOn( RefPtr blocker = new ServiceWorkerShutdownBlocker(); - nsresult rv = aShutdownBarrier->AddBlocker( - blocker.get(), NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("Service Workers shutdown")); + nsresult rv = + aShutdownBarrier->AddBlocker(blocker.get(), NS_LITERAL_STRING(__FILE__), + __LINE__, u"Service Workers shutdown"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return nullptr; diff --git a/dom/serviceworkers/ServiceWorkerUpdateJob.cpp b/dom/serviceworkers/ServiceWorkerUpdateJob.cpp index cfd33035d8a7..1d97c7db0c5a 100644 --- a/dom/serviceworkers/ServiceWorkerUpdateJob.cpp +++ b/dom/serviceworkers/ServiceWorkerUpdateJob.cpp @@ -489,8 +489,7 @@ void ServiceWorkerUpdateJob::Install() { // Send the install event to the worker thread ServiceWorkerPrivate* workerPrivate = mRegistration->GetInstalling()->WorkerPrivate(); - nsresult rv = - workerPrivate->SendLifeCycleEvent(NS_LITERAL_STRING("install"), callback); + nsresult rv = workerPrivate->SendLifeCycleEvent(u"install"_ns, callback); if (NS_WARN_IF(NS_FAILED(rv))) { ContinueAfterInstallEvent(false /* aSuccess */); } diff --git a/dom/serviceworkers/ServiceWorkerUtils.cpp b/dom/serviceworkers/ServiceWorkerUtils.cpp index b1bd3e2b7cb1..e295ae409c5d 100644 --- a/dom/serviceworkers/ServiceWorkerUtils.cpp +++ b/dom/serviceworkers/ServiceWorkerUtils.cpp @@ -93,10 +93,9 @@ void ServiceWorkerScopeAndScriptAreValid(const ClientInfo& aClientInfo, // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 3. if (!hasValidURISchemes(aScriptURI)) { - auto message = - !isExtension - ? NS_LITERAL_CSTRING("Script URL's scheme is not 'http' or 'https'") - : NS_LITERAL_CSTRING("Script URL's scheme is not 'moz-extension'"); + auto message = !isExtension + ? "Script URL's scheme is not 'http' or 'https'"_ns + : "Script URL's scheme is not 'moz-extension'"_ns; aRv.ThrowTypeError(message); return; } @@ -109,10 +108,9 @@ void ServiceWorkerScopeAndScriptAreValid(const ClientInfo& aClientInfo, // https://w3c.github.io/ServiceWorker/#start-register-algorithm step 8. if (!hasValidURISchemes(aScopeURI)) { - auto message = - !isExtension - ? NS_LITERAL_CSTRING("Scope URL's scheme is not 'http' or 'https'") - : NS_LITERAL_CSTRING("Scope URL's scheme is not 'moz-extension'"); + auto message = !isExtension + ? "Scope URL's scheme is not 'http' or 'https'"_ns + : "Scope URL's scheme is not 'moz-extension'"_ns; aRv.ThrowTypeError(message); return; } diff --git a/dom/serviceworkers/test/gtest/TestReadWrite.cpp b/dom/serviceworkers/test/gtest/TestReadWrite.cpp index 2eb681a048cd..9fffcdbd2bf6 100644 --- a/dom/serviceworkers/test/gtest/TestReadWrite.cpp +++ b/dom/serviceworkers/test/gtest/TestReadWrite.cpp @@ -123,8 +123,7 @@ TEST(ServiceWorkerRegistrar, TestEmptyFile) TEST(ServiceWorkerRegistrar, TestRightVersionFile) { - ASSERT_TRUE( - CreateFile(NS_LITERAL_CSTRING(SERVICEWORKERREGISTRAR_VERSION "\n"))) + ASSERT_TRUE(CreateFile(nsLiteralCString(SERVICEWORKERREGISTRAR_VERSION "\n"))) << "CreateFile should not fail"; RefPtr swr = new ServiceWorkerRegistrarTest; @@ -141,7 +140,7 @@ TEST(ServiceWorkerRegistrar, TestRightVersionFile) TEST(ServiceWorkerRegistrar, TestWrongVersionFile) { ASSERT_TRUE( - CreateFile(NS_LITERAL_CSTRING(SERVICEWORKERREGISTRAR_VERSION "bla\n"))) + CreateFile(nsLiteralCString(SERVICEWORKERREGISTRAR_VERSION "bla\n"))) << "CreateFile should not fail"; RefPtr swr = new ServiceWorkerRegistrarTest; @@ -243,7 +242,7 @@ TEST(ServiceWorkerRegistrar, TestReadData) TEST(ServiceWorkerRegistrar, TestDeleteData) { - ASSERT_TRUE(CreateFile(NS_LITERAL_CSTRING("Foobar"))) + ASSERT_TRUE(CreateFile("Foobar"_ns)) << "CreateFile should not fail"; RefPtr swr = new ServiceWorkerRegistrarTest; @@ -876,7 +875,7 @@ TEST(ServiceWorkerRegistrar, TestDedupeWrite) for (int i = 0; i < 2; ++i) { ServiceWorkerRegistrationData reg; - reg.scope() = NS_LITERAL_CSTRING("https://scope_write.dedupe"); + reg.scope() = "https://scope_write.dedupe"_ns; reg.currentWorkerURL() = nsPrintfCString("currentWorkerURL write %d", i); reg.currentWorkerHandlesFetch() = true; reg.cacheName() = diff --git a/dom/smil/SMILCSSValueType.cpp b/dom/smil/SMILCSSValueType.cpp index 204ae31f0088..e7b32fbb3b4a 100644 --- a/dom/smil/SMILCSSValueType.cpp +++ b/dom/smil/SMILCSSValueType.cpp @@ -490,8 +490,7 @@ SMILValue SMILCSSValueType::ValueFromAnimationValue( // string passed to CSPAllowsInlineStyle is only used for reporting violations // and an intermediate CSS value is not likely to be particularly useful // in that case, we just use a generic placeholder string instead. - static const nsLiteralString kPlaceholderText = - NS_LITERAL_STRING("[SVG animation of CSS]"); + static const nsLiteralString kPlaceholderText = u"[SVG animation of CSS]"_ns; if (doc && !nsStyleUtil::CSPAllowsInlineStyle(nullptr, doc, nullptr, 0, 0, kPlaceholderText, nullptr)) { return result; diff --git a/dom/smil/SMILParserUtils.cpp b/dom/smil/SMILParserUtils.cpp index ef29ed96af66..5837c429043d 100644 --- a/dom/smil/SMILParserUtils.cpp +++ b/dom/smil/SMILParserUtils.cpp @@ -30,10 +30,10 @@ const uint32_t MSEC_PER_SEC = 1000; const uint32_t MSEC_PER_MIN = 1000 * 60; const uint32_t MSEC_PER_HOUR = 1000 * 60 * 60; -#define ACCESSKEY_PREFIX_LC NS_LITERAL_STRING("accesskey(") // SMIL2+ -#define ACCESSKEY_PREFIX_CC NS_LITERAL_STRING("accessKey(") // SVG/SMIL ANIM -#define REPEAT_PREFIX NS_LITERAL_STRING("repeat(") -#define WALLCLOCK_PREFIX NS_LITERAL_STRING("wallclock(") +#define ACCESSKEY_PREFIX_LC u"accesskey("_ns // SMIL2+ +#define ACCESSKEY_PREFIX_CC u"accessKey("_ns // SVG/SMIL ANIM +#define REPEAT_PREFIX u"repeat("_ns +#define WALLCLOCK_PREFIX u"wallclock("_ns inline bool SkipWhitespace(RangedPtr& aIter, const RangedPtr& aEnd) { diff --git a/dom/storage/LocalStorageCache.cpp b/dom/storage/LocalStorageCache.cpp index f3b71ee5f9b7..1f3ec3f9a0d3 100644 --- a/dom/storage/LocalStorageCache.cpp +++ b/dom/storage/LocalStorageCache.cpp @@ -148,7 +148,7 @@ void LocalStorageCache::Init(LocalStorageManager* aManager, bool aPersistent, // this storage cache is bound to. MOZ_ASSERT(StringBeginsWith(mQuotaOriginScope, mOriginSuffix)); MOZ_ASSERT(mOriginSuffix.IsEmpty() != - StringBeginsWith(mQuotaOriginScope, NS_LITERAL_CSTRING("^"))); + StringBeginsWith(mQuotaOriginScope, "^"_ns)); mUsage = aManager->GetOriginUsage(mQuotaOriginScope); } diff --git a/dom/storage/Storage.cpp b/dom/storage/Storage.cpp index f7bf6c95a51d..4819d563557c 100644 --- a/dom/storage/Storage.cpp +++ b/dom/storage/Storage.cpp @@ -120,7 +120,7 @@ void Storage::NotifyChange(Storage* aStorage, nsIPrincipal* aPrincipal, // Note, this DOM event should never reach JS. It is cloned later in // nsGlobalWindow. RefPtr event = - StorageEvent::Constructor(nullptr, NS_LITERAL_STRING("storage"), dict); + StorageEvent::Constructor(nullptr, u"storage"_ns, dict); event->SetPrincipal(aPrincipal); diff --git a/dom/storage/StorageDBThread.cpp b/dom/storage/StorageDBThread.cpp index e972b6e9df48..bfc96f4111d3 100644 --- a/dom/storage/StorageDBThread.cpp +++ b/dom/storage/StorageDBThread.cpp @@ -208,7 +208,7 @@ nsresult StorageDBThread::Init(const nsString& aProfilePath) { return rv; } - rv = mDatabaseFile->Append(NS_LITERAL_STRING("webappsstore.sqlite")); + rv = mDatabaseFile->Append(u"webappsstore.sqlite"_ns); NS_ENSURE_SUCCESS(rv, rv); // Need to keep the lock to avoid setting mThread later then @@ -589,8 +589,8 @@ nsresult StorageDBThread::InitDatabase() { nsCOMPtr stmt; // Note: result of this select must match StorageManager::CreateOrigin() rv = mWorkerConnection->CreateStatement( - NS_LITERAL_CSTRING("SELECT DISTINCT originAttributes || ':' || originKey " - "FROM webappsstore2"), + nsLiteralCString("SELECT DISTINCT originAttributes || ':' || originKey " + "FROM webappsstore2"), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); mozStorageStatementScoper scope(stmt); @@ -665,7 +665,7 @@ nsresult StorageDBThread::ConfigureWALBehavior() { // Get the DB's page size nsCOMPtr stmt; nsresult rv = mWorkerConnection->CreateStatement( - NS_LITERAL_CSTRING(MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA page_size"), + nsLiteralCString(MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA page_size"), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); @@ -893,7 +893,7 @@ const nsCString StorageDBThread::DBOperation::Target() const { case opAddItem: case opUpdateItem: case opRemoveItem: - return Origin() + NS_LITERAL_CSTRING("|") + NS_ConvertUTF16toUTF8(mKey); + return Origin() + "|"_ns + NS_ConvertUTF16toUTF8(mKey); default: return Origin(); @@ -934,15 +934,14 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), + rv = stmt->BindUTF8StringByName("originAttributes"_ns, mCache->OriginSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - mCache->OriginNoSuffix()); + rv = stmt->BindUTF8StringByName("originKey"_ns, mCache->OriginNoSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("offset"), + rv = stmt->BindInt32ByName("offset"_ns, static_cast(mCache->LoadedCount())); NS_ENSURE_SUCCESS(rv, rv); @@ -976,8 +975,7 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("usageOrigin"), - mUsage->OriginScope()); + rv = stmt->BindUTF8StringByName("usageOrigin"_ns, mUsage->OriginScope()); NS_ENSURE_SUCCESS(rv, rv); bool exists; @@ -1007,20 +1005,19 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), + rv = stmt->BindUTF8StringByName("originAttributes"_ns, mCache->OriginSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - mCache->OriginNoSuffix()); + rv = stmt->BindUTF8StringByName("originKey"_ns, mCache->OriginNoSuffix()); NS_ENSURE_SUCCESS(rv, rv); // Filling the 'scope' column just for downgrade compatibility reasons rv = stmt->BindUTF8StringByName( - NS_LITERAL_CSTRING("scope"), + "scope"_ns, Scheme0Scope(mCache->OriginSuffix(), mCache->OriginNoSuffix())); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), mKey); + rv = stmt->BindStringByName("key"_ns, mKey); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("value"), mValue); + rv = stmt->BindStringByName("value"_ns, mValue); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1043,13 +1040,12 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), + rv = stmt->BindUTF8StringByName("originAttributes"_ns, mCache->OriginSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - mCache->OriginNoSuffix()); + rv = stmt->BindUTF8StringByName("originKey"_ns, mCache->OriginNoSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("key"), mKey); + rv = stmt->BindStringByName("key"_ns, mKey); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1069,11 +1065,10 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), + rv = stmt->BindUTF8StringByName("originAttributes"_ns, mCache->OriginSuffix()); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("originKey"), - mCache->OriginNoSuffix()); + rv = stmt->BindUTF8StringByName("originKey"_ns, mCache->OriginNoSuffix()); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1111,8 +1106,7 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scope(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("scope"), - mOrigin + NS_LITERAL_CSTRING("*")); + rv = stmt->BindUTF8StringByName("scope"_ns, mOrigin + "*"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1133,8 +1127,7 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { new OriginAttrsPatternMatchSQLFunction(mOriginPattern)); rv = aThread->mWorkerConnection->CreateFunction( - NS_LITERAL_CSTRING("ORIGIN_ATTRS_PATTERN_MATCH"), 1, - patternMatchFunction); + "ORIGIN_ATTRS_PATTERN_MATCH"_ns, 1, patternMatchFunction); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr stmt = @@ -1151,7 +1144,7 @@ nsresult StorageDBThread::DBOperation::Perform(StorageDBThread* aThread) { // Always remove the function aThread->mWorkerConnection->RemoveFunction( - NS_LITERAL_CSTRING("ORIGIN_ATTRS_PATTERN_MATCH")); + "ORIGIN_ATTRS_PATTERN_MATCH"_ns); NS_ENSURE_SUCCESS(rv, rv); diff --git a/dom/storage/StorageDBUpdater.cpp b/dom/storage/StorageDBUpdater.cpp index ad6123fea767..7ca81b29d520 100644 --- a/dom/storage/StorageDBUpdater.cpp +++ b/dom/storage/StorageDBUpdater.cpp @@ -233,7 +233,7 @@ namespace StorageDBUpdater { nsresult CreateSchema1Tables(mozIStorageConnection* aWorkerConnection) { nsresult rv; - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE IF NOT EXISTS webappsstore2 (" "originAttributes TEXT, " "originKey TEXT, " @@ -242,9 +242,9 @@ nsresult CreateSchema1Tables(mozIStorageConnection* aWorkerConnection) { "value TEXT)")); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "CREATE UNIQUE INDEX IF NOT EXISTS origin_key_index" - " ON webappsstore2(originAttributes, originKey, key)")); + rv = aWorkerConnection->ExecuteSimpleSQL( + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS origin_key_index" + " ON webappsstore2(originAttributes, originKey, key)")); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -264,7 +264,7 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { // downgrade (v0) -> upgrade (v1+) specific code if (schemaVer >= 1) { bool schema0IndexExists; - rv = aWorkerConnection->IndexExists(NS_LITERAL_CSTRING("scope_key_index"), + rv = aWorkerConnection->IndexExists("scope_key_index"_ns, &schema0IndexExists); NS_ENSURE_SUCCESS(rv, rv); @@ -283,14 +283,14 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { case 0: { bool webappsstore2Exists, webappsstoreExists, moz_webappsstoreExists; - rv = aWorkerConnection->TableExists(NS_LITERAL_CSTRING("webappsstore2"), + rv = aWorkerConnection->TableExists("webappsstore2"_ns, &webappsstore2Exists); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->TableExists(NS_LITERAL_CSTRING("webappsstore"), + rv = aWorkerConnection->TableExists("webappsstore"_ns, &webappsstoreExists); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->TableExists( - NS_LITERAL_CSTRING("moz_webappsstore"), &moz_webappsstoreExists); + rv = aWorkerConnection->TableExists("moz_webappsstore"_ns, + &moz_webappsstoreExists); NS_ENSURE_SUCCESS(rv, rv); if (!webappsstore2Exists && !webappsstoreExists && @@ -312,24 +312,23 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { // Ensure Gecko 1.9.1 storage table rv = aWorkerConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS webappsstore2 (" - "scope TEXT, " - "key TEXT, " - "value TEXT, " - "secure INTEGER, " - "owner TEXT)")); + nsLiteralCString("CREATE TABLE IF NOT EXISTS webappsstore2 (" + "scope TEXT, " + "key TEXT, " + "value TEXT, " + "secure INTEGER, " + "owner TEXT)")); NS_ENSURE_SUCCESS(rv, rv); rv = aWorkerConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE UNIQUE INDEX IF NOT EXISTS scope_key_index" - " ON webappsstore2(scope, key)")); + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS scope_key_index" + " ON webappsstore2(scope, key)")); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr function1(new nsReverseStringSQLFunction()); NS_ENSURE_TRUE(function1, NS_ERROR_OUT_OF_MEMORY); - rv = aWorkerConnection->CreateFunction( - NS_LITERAL_CSTRING("REVERSESTRING"), 1, function1); + rv = aWorkerConnection->CreateFunction("REVERSESTRING"_ns, 1, function1); NS_ENSURE_SUCCESS(rv, rv); // Check if there is storage of Gecko 1.9.0 and if so, upgrade that @@ -337,15 +336,14 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { // First process this newer table upgrade to priority potential duplicates // from older storage table. if (webappsstoreExists) { - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO " "webappsstore2(scope, key, value, secure, owner) " "SELECT REVERSESTRING(domain) || '.:', key, value, secure, owner " "FROM webappsstore")); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE webappsstore")); + rv = aWorkerConnection->ExecuteSimpleSQL("DROP TABLE webappsstore"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -353,7 +351,7 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { // to actual webappsstore2 table and drop the obsolete table. Potential // duplicates will be ignored. if (moz_webappsstoreExists) { - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO " "webappsstore2(scope, key, value, secure, owner) " "SELECT REVERSESTRING(domain) || '.:', key, value, secure, domain " @@ -361,46 +359,46 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { NS_ENSURE_SUCCESS(rv, rv); rv = aWorkerConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_webappsstore")); + "DROP TABLE moz_webappsstore"_ns); NS_ENSURE_SUCCESS(rv, rv); } - aWorkerConnection->RemoveFunction(NS_LITERAL_CSTRING("REVERSESTRING")); + aWorkerConnection->RemoveFunction("REVERSESTRING"_ns); // Update the scoping to match the new implememntation: split to oa suffix // and origin key First rename the old table, we want to remove some // columns no longer needed, but even before that drop all indexes from it // (CREATE IF NOT EXISTS for index on the new table would falsely find the // index!) - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "DROP INDEX IF EXISTS webappsstore2.origin_key_index")); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "DROP INDEX IF EXISTS webappsstore2.scope_key_index")); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE webappsstore2 RENAME TO webappsstore2_old")); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr oaSuffixFunc(new GetOriginParticular( GetOriginParticular::ORIGIN_ATTRIBUTES_SUFFIX)); - rv = aWorkerConnection->CreateFunction( - NS_LITERAL_CSTRING("GET_ORIGIN_SUFFIX"), 1, oaSuffixFunc); + rv = aWorkerConnection->CreateFunction("GET_ORIGIN_SUFFIX"_ns, 1, + oaSuffixFunc); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr originKeyFunc( new GetOriginParticular(GetOriginParticular::ORIGIN_KEY)); - rv = aWorkerConnection->CreateFunction( - NS_LITERAL_CSTRING("GET_ORIGIN_KEY"), 1, originKeyFunc); + rv = aWorkerConnection->CreateFunction("GET_ORIGIN_KEY"_ns, 1, + originKeyFunc); NS_ENSURE_SUCCESS(rv, rv); // Here we ensure this schema tables when we are updating. rv = CreateSchema1Tables(aWorkerConnection); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO " "webappsstore2 (originAttributes, originKey, scope, key, value) " "SELECT GET_ORIGIN_SUFFIX(scope), GET_ORIGIN_KEY(scope), scope, key, " @@ -409,12 +407,11 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { NS_ENSURE_SUCCESS(rv, rv); rv = aWorkerConnection->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE webappsstore2_old")); + "DROP TABLE webappsstore2_old"_ns); NS_ENSURE_SUCCESS(rv, rv); - aWorkerConnection->RemoveFunction( - NS_LITERAL_CSTRING("GET_ORIGIN_SUFFIX")); - aWorkerConnection->RemoveFunction(NS_LITERAL_CSTRING("GET_ORIGIN_KEY")); + aWorkerConnection->RemoveFunction("GET_ORIGIN_SUFFIX"_ns); + aWorkerConnection->RemoveFunction("GET_ORIGIN_KEY"_ns); rv = aWorkerConnection->SetSchemaVersion(1); NS_ENSURE_SUCCESS(rv, rv); @@ -423,17 +420,17 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { } case 1: { nsCOMPtr oaStripAddonId(new StripOriginAddonId()); - rv = aWorkerConnection->CreateFunction( - NS_LITERAL_CSTRING("STRIP_ADDON_ID"), 1, oaStripAddonId); + rv = aWorkerConnection->CreateFunction("STRIP_ADDON_ID"_ns, 1, + oaStripAddonId); NS_ENSURE_SUCCESS(rv, rv); - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = aWorkerConnection->ExecuteSimpleSQL(nsLiteralCString( "UPDATE webappsstore2 " "SET originAttributes = STRIP_ADDON_ID(originAttributes) " "WHERE originAttributes LIKE '^%'")); NS_ENSURE_SUCCESS(rv, rv); - aWorkerConnection->RemoveFunction(NS_LITERAL_CSTRING("STRIP_ADDON_ID")); + aWorkerConnection->RemoveFunction("STRIP_ADDON_ID"_ns); rv = aWorkerConnection->SetSchemaVersion(2); NS_ENSURE_SUCCESS(rv, rv); @@ -460,7 +457,7 @@ nsresult Update(mozIStorageConnection* aWorkerConnection) { if (doVacuum) { // In some cases this can make the disk file of the database significantly // smaller. VACUUM cannot be executed inside a transaction. - rv = aWorkerConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM")); + rv = aWorkerConnection->ExecuteSimpleSQL("VACUUM"_ns); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/dom/storage/StorageObserver.cpp b/dom/storage/StorageObserver.cpp index 50a763d880f1..b8c5cca21dd1 100644 --- a/dom/storage/StorageObserver.cpp +++ b/dom/storage/StorageObserver.cpp @@ -209,7 +209,7 @@ StorageObserver::Observe(nsISupports* aSubject, const char* aTopic, // Clear everything, caches + database if (!strcmp(aTopic, "cookie-changed")) { - if (!NS_LITERAL_STRING("cleared").Equals(aData)) { + if (!u"cleared"_ns.Equals(aData)) { return NS_OK; } @@ -242,14 +242,14 @@ StorageObserver::Observe(nsISupports* aSubject, const char* aTopic, nsAutoCString type; perm->GetType(type); - if (type != NS_LITERAL_CSTRING("cookie")) { + if (type != "cookie"_ns) { return NS_OK; } uint32_t cap = 0; perm->GetCapability(&cap); if (!(cap & nsICookiePermission::ACCESS_SESSION) || - !NS_LITERAL_STRING("deleted").Equals(nsDependentString(aData))) { + !u"deleted"_ns.Equals(nsDependentString(aData))) { return NS_OK; } diff --git a/dom/svg/SVGContentUtils.cpp b/dom/svg/SVGContentUtils.cpp index e0084dc3a3e0..c718161a0178 100644 --- a/dom/svg/SVGContentUtils.cpp +++ b/dom/svg/SVGContentUtils.cpp @@ -441,9 +441,9 @@ float SVGContentUtils::GetFontXHeight(ComputedStyle* aComputedStyle, } nsresult SVGContentUtils::ReportToConsole(Document* doc, const char* aWarning, const nsTArray& aParams) { - return nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("SVG"), doc, - nsContentUtils::eSVG_PROPERTIES, aWarning, aParams); + return nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "SVG"_ns, + doc, nsContentUtils::eSVG_PROPERTIES, + aWarning, aParams); } bool SVGContentUtils::EstablishesViewport(nsIContent* aContent) { diff --git a/dom/svg/SVGFragmentIdentifier.cpp b/dom/svg/SVGFragmentIdentifier.cpp index 7e3c04517d6a..55fd6d8f31cf 100644 --- a/dom/svg/SVGFragmentIdentifier.cpp +++ b/dom/svg/SVGFragmentIdentifier.cpp @@ -71,20 +71,19 @@ class MOZ_RAII AutoSVGViewHandler { // If we encounter any attribute more than once or get any syntax errors // we're going to return false and cancel any changes. - if (IsMatchingParameter(aToken, NS_LITERAL_STRING("viewBox"))) { + if (IsMatchingParameter(aToken, u"viewBox"_ns)) { if (mSVGView->mViewBox.IsExplicitlySet() || NS_FAILED( mSVGView->mViewBox.SetBaseValueString(aParams, mRoot, false))) { return false; } - } else if (IsMatchingParameter(aToken, - NS_LITERAL_STRING("preserveAspectRatio"))) { + } else if (IsMatchingParameter(aToken, u"preserveAspectRatio"_ns)) { if (mSVGView->mPreserveAspectRatio.IsExplicitlySet() || NS_FAILED(mSVGView->mPreserveAspectRatio.SetBaseValueString( aParams, mRoot, false))) { return false; } - } else if (IsMatchingParameter(aToken, NS_LITERAL_STRING("transform"))) { + } else if (IsMatchingParameter(aToken, u"transform"_ns)) { if (mSVGView->mTransforms) { return false; } @@ -93,7 +92,7 @@ class MOZ_RAII AutoSVGViewHandler { mSVGView->mTransforms->SetBaseValueString(aParams, mRoot))) { return false; } - } else if (IsMatchingParameter(aToken, NS_LITERAL_STRING("zoomAndPan"))) { + } else if (IsMatchingParameter(aToken, u"zoomAndPan"_ns)) { if (mSVGView->mZoomAndPan.IsExplicitlySet()) { return false; } @@ -121,7 +120,7 @@ bool SVGFragmentIdentifier::ProcessSVGViewSpec(const nsAString& aViewSpec, SVGSVGElement* aRoot) { AutoSVGViewHandler viewHandler(aRoot); - if (!IsMatchingParameter(aViewSpec, NS_LITERAL_STRING("svgView"))) { + if (!IsMatchingParameter(aViewSpec, u"svgView"_ns)) { return false; } diff --git a/dom/svg/SVGScriptElement.cpp b/dom/svg/SVGScriptElement.cpp index 369eb3293f29..800e29e4e1a0 100644 --- a/dom/svg/SVGScriptElement.cpp +++ b/dom/svg/SVGScriptElement.cpp @@ -132,23 +132,20 @@ void SVGScriptElement::FreezeExecutionAttrs(Document* aOwnerDoc) { NS_NewURI(getter_AddRefs(mUri), src, nullptr, GetBaseURI()); if (!mUri) { - AutoTArray params = {isHref - ? NS_LITERAL_STRING("href") - : NS_LITERAL_STRING("xlink:href"), - src}; + AutoTArray params = { + isHref ? u"href"_ns : u"xlink:href"_ns, src}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("SVG"), OwnerDoc(), + nsIScriptError::warningFlag, "SVG"_ns, OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, "ScriptSourceInvalidUri", params, nullptr, EmptyString(), GetScriptLineNumber(), GetScriptColumnNumber()); } } else { - AutoTArray params = { - isHref ? NS_LITERAL_STRING("href") : NS_LITERAL_STRING("xlink:href")}; + AutoTArray params = {isHref ? u"href"_ns : u"xlink:href"_ns}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("SVG"), OwnerDoc(), + nsIScriptError::warningFlag, "SVG"_ns, OwnerDoc(), nsContentUtils::eDOM_PROPERTIES, "ScriptSourceEmpty", params, nullptr, EmptyString(), GetScriptLineNumber(), GetScriptColumnNumber()); } diff --git a/dom/system/linux/GpsdLocationProvider.cpp b/dom/system/linux/GpsdLocationProvider.cpp index a4ff514e0bfe..f25949a36080 100644 --- a/dom/system/linux/GpsdLocationProvider.cpp +++ b/dom/system/linux/GpsdLocationProvider.cpp @@ -370,9 +370,9 @@ GpsdLocationProvider::Startup() { // ... or create a new one. if (!pollThread) { - pollThread = MakeAndAddRef( - GPSD_POLL_THREAD_TIMEOUT_MS, NS_LITERAL_CSTRING("Gpsd poll thread"), - LazyIdleThread::ManualShutdown); + pollThread = MakeAndAddRef(GPSD_POLL_THREAD_TIMEOUT_MS, + "Gpsd poll thread"_ns, + LazyIdleThread::ManualShutdown); } auto rv = pollThread->Dispatch(pollRunnable, NS_DISPATCH_NORMAL); diff --git a/dom/system/nsDeviceSensors.cpp b/dom/system/nsDeviceSensors.cpp index b313be98eb6c..ce63983983f2 100644 --- a/dom/system/nsDeviceSensors.cpp +++ b/dom/system/nsDeviceSensors.cpp @@ -347,8 +347,8 @@ void nsDeviceSensors::FireDOMLightEvent(mozilla::dom::EventTarget* aTarget, init.mBubbles = true; init.mCancelable = false; init.mValue = round(aValue); - RefPtr event = DeviceLightEvent::Constructor( - aTarget, NS_LITERAL_STRING("devicelight"), init); + RefPtr event = + DeviceLightEvent::Constructor(aTarget, u"devicelight"_ns, init); event->SetTrusted(true); @@ -364,8 +364,8 @@ void nsDeviceSensors::FireDOMProximityEvent(mozilla::dom::EventTarget* aTarget, init.mValue = aValue; init.mMin = aMin; init.mMax = aMax; - RefPtr event = DeviceProximityEvent::Constructor( - aTarget, NS_LITERAL_STRING("deviceproximity"), init); + RefPtr event = + DeviceProximityEvent::Constructor(aTarget, u"deviceproximity"_ns, init); event->SetTrusted(true); aTarget->DispatchEvent(*event); @@ -388,8 +388,8 @@ void nsDeviceSensors::FireDOMUserProximityEvent( init.mBubbles = true; init.mCancelable = false; init.mNear = aNear; - RefPtr event = UserProximityEvent::Constructor( - aTarget, NS_LITERAL_STRING("userproximity"), init); + RefPtr event = + UserProximityEvent::Constructor(aTarget, u"userproximity"_ns, init); event->SetTrusted(true); @@ -414,8 +414,8 @@ void nsDeviceSensors::FireDOMOrientationEvent(EventTarget* aTarget, aEventTarget->DispatchEvent(*event); }; - Dispatch(aTarget, aIsAbsolute ? NS_LITERAL_STRING("absolutedeviceorientation") - : NS_LITERAL_STRING("deviceorientation")); + Dispatch(aTarget, aIsAbsolute ? u"absolutedeviceorientation"_ns + : u"deviceorientation"_ns); // This is used to determine whether relative events have been dispatched // during the current session, in which case we don't dispatch the additional @@ -430,7 +430,7 @@ void nsDeviceSensors::FireDOMOrientationEvent(EventTarget* aTarget, // For absolute events on devices without support for relative events, // we need to additionally dispatch type "deviceorientation" to keep // backwards-compatibility. - Dispatch(aTarget, NS_LITERAL_STRING("deviceorientation")); + Dispatch(aTarget, u"deviceorientation"_ns); } } @@ -487,8 +487,8 @@ void nsDeviceSensors::FireDOMMotionEvent(Document* doc, EventTarget* target, } IgnoredErrorResult ignored; - RefPtr event = doc->CreateEvent(NS_LITERAL_STRING("DeviceMotionEvent"), - CallerType::System, ignored); + RefPtr event = + doc->CreateEvent(u"DeviceMotionEvent"_ns, CallerType::System, ignored); if (!event) { return; } @@ -496,7 +496,7 @@ void nsDeviceSensors::FireDOMMotionEvent(Document* doc, EventTarget* target, DeviceMotionEvent* me = static_cast(event.get()); me->InitDeviceMotionEvent( - NS_LITERAL_STRING("devicemotion"), true, false, *mLastAcceleration, + u"devicemotion"_ns, true, false, *mLastAcceleration, *mLastAccelerationIncludingGravity, *mLastRotationRate, Nullable(DEFAULT_SENSOR_POLL), Nullable(timestamp)); diff --git a/dom/url/URLSearchParams.cpp b/dom/url/URLSearchParams.cpp index 4602e1d7c5dc..1ddceb0e146d 100644 --- a/dom/url/URLSearchParams.cpp +++ b/dom/url/URLSearchParams.cpp @@ -326,7 +326,7 @@ already_AddRefed URLSearchParams::Constructor( if (aInit.IsUSVString()) { NS_ConvertUTF16toUTF8 input(aInit.GetAsUSVString()); - if (StringBeginsWith(input, NS_LITERAL_CSTRING("?"))) { + if (StringBeginsWith(input, "?"_ns)) { sp->ParseInput(Substring(input, 1, input.Length() - 1)); } else { sp->ParseInput(input); diff --git a/dom/url/URLWorker.cpp b/dom/url/URLWorker.cpp index 1d29cd881fa9..c06649a92337 100644 --- a/dom/url/URLWorker.cpp +++ b/dom/url/URLWorker.cpp @@ -24,8 +24,7 @@ class CreateURLRunnable : public WorkerMainThreadRunnable { public: CreateURLRunnable(WorkerPrivate* aWorkerPrivate, BlobImpl* aBlobImpl, nsAString& aURL) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("URL :: CreateURL")), + : WorkerMainThreadRunnable(aWorkerPrivate, "URL :: CreateURL"_ns), mBlobImpl(aBlobImpl), mURL(aURL) { MOZ_ASSERT(aBlobImpl); @@ -60,8 +59,7 @@ class RevokeURLRunnable : public WorkerMainThreadRunnable { public: RevokeURLRunnable(WorkerPrivate* aWorkerPrivate, const nsAString& aURL) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("URL :: RevokeURL")), + : WorkerMainThreadRunnable(aWorkerPrivate, "URL :: RevokeURL"_ns), mURL(aURL) {} bool MainThreadRun() override { @@ -93,8 +91,7 @@ class IsValidURLRunnable : public WorkerMainThreadRunnable { public: IsValidURLRunnable(WorkerPrivate* aWorkerPrivate, const nsAString& aURL) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("URL :: IsValidURL")), + : WorkerMainThreadRunnable(aWorkerPrivate, "URL :: IsValidURL"_ns), mURL(aURL), mValid(false) {} diff --git a/dom/vr/XRInputSource.cpp b/dom/vr/XRInputSource.cpp index 30e53a57d954..5e20f3b92275 100644 --- a/dom/vr/XRInputSource.cpp +++ b/dom/vr/XRInputSource.cpp @@ -219,11 +219,11 @@ void XRInputSource::SetGamepadIsConnected(bool aConnected, if (!aConnected) { if (mSelectAction != ActionState::ActionState_Released) { - DispatchEvent(NS_LITERAL_STRING("selectend"), aSession); + DispatchEvent(u"selectend"_ns, aSession); mSelectAction = ActionState::ActionState_Released; } if (mSqueezeAction != ActionState::ActionState_Released) { - DispatchEvent(NS_LITERAL_STRING("squeezeend"), aSession); + DispatchEvent(u"squeezeend"_ns, aSession); mSqueezeAction = ActionState::ActionState_Released; } } @@ -284,7 +284,7 @@ void XRInputSource::Update(XRSession* aSession) { controllerState.selectActionStopFrameId) { if (mSelectAction == ActionState::ActionState_Released && controllerState.triggerValue[selectIndex] > endThreshold) { - DispatchEvent(NS_LITERAL_STRING("selectstart"), aSession); + DispatchEvent(u"selectstart"_ns, aSession); mSelectAction = ActionState::ActionState_Pressing; } else if (mSelectAction == ActionState::ActionState_Pressing && controllerState.triggerValue[selectIndex] > @@ -292,23 +292,23 @@ void XRInputSource::Update(XRSession* aSession) { mSelectAction = ActionState::ActionState_Pressed; } else if (mSelectAction == ActionState::ActionState_Pressed && controllerState.triggerValue[selectIndex] < startThreshold) { - DispatchEvent(NS_LITERAL_STRING("select"), aSession); + DispatchEvent(u"select"_ns, aSession); mSelectAction = ActionState::ActionState_Releasing; } else if (mSelectAction <= ActionState::ActionState_Releasing && controllerState.triggerValue[selectIndex] < endThreshold) { // For a select btn which only has pressed and unpressed status. if (mSelectAction == ActionState::ActionState_Pressed) { - DispatchEvent(NS_LITERAL_STRING("select"), aSession); + DispatchEvent(u"select"_ns, aSession); } - DispatchEvent(NS_LITERAL_STRING("selectend"), aSession); + DispatchEvent(u"selectend"_ns, aSession); mSelectAction = ActionState::ActionState_Released; } } else if (mSelectAction <= ActionState::ActionState_Releasing) { // For a select btn which only has pressed and unpressed status. if (mSelectAction == ActionState::ActionState_Pressed) { - DispatchEvent(NS_LITERAL_STRING("select"), aSession); + DispatchEvent(u"select"_ns, aSession); } - DispatchEvent(NS_LITERAL_STRING("selectend"), aSession); + DispatchEvent(u"selectend"_ns, aSession); mSelectAction = ActionState::ActionState_Released; } } @@ -319,7 +319,7 @@ void XRInputSource::Update(XRSession* aSession) { controllerState.squeezeActionStopFrameId) { if (mSqueezeAction == ActionState::ActionState_Released && controllerState.triggerValue[squeezeIndex] > endThreshold) { - DispatchEvent(NS_LITERAL_STRING("squeezestart"), aSession); + DispatchEvent(u"squeezestart"_ns, aSession); mSqueezeAction = ActionState::ActionState_Pressing; } else if (mSqueezeAction == ActionState::ActionState_Pressing && controllerState.triggerValue[squeezeIndex] > @@ -327,23 +327,23 @@ void XRInputSource::Update(XRSession* aSession) { mSqueezeAction = ActionState::ActionState_Pressed; } else if (mSqueezeAction == ActionState::ActionState_Pressed && controllerState.triggerValue[squeezeIndex] < startThreshold) { - DispatchEvent(NS_LITERAL_STRING("squeeze"), aSession); + DispatchEvent(u"squeeze"_ns, aSession); mSqueezeAction = ActionState::ActionState_Releasing; } else if (mSqueezeAction <= ActionState::ActionState_Releasing && controllerState.triggerValue[squeezeIndex] < endThreshold) { // For a squeeze btn which only has pressed and unpressed status. if (mSqueezeAction == ActionState::ActionState_Pressed) { - DispatchEvent(NS_LITERAL_STRING("squeeze"), aSession); + DispatchEvent(u"squeeze"_ns, aSession); } - DispatchEvent(NS_LITERAL_STRING("squeezeend"), aSession); + DispatchEvent(u"squeezeend"_ns, aSession); mSqueezeAction = ActionState::ActionState_Released; } } else if (mSqueezeAction <= ActionState::ActionState_Releasing) { // For a squeeze btn which only has pressed and unpressed status. if (mSqueezeAction == ActionState::ActionState_Pressed) { - DispatchEvent(NS_LITERAL_STRING("squeeze"), aSession); + DispatchEvent(u"squeeze"_ns, aSession); } - DispatchEvent(NS_LITERAL_STRING("squeezeend"), aSession); + DispatchEvent(u"squeezeend"_ns, aSession); mSqueezeAction = ActionState::ActionState_Released; } } diff --git a/dom/vr/XRInputSourceArray.cpp b/dom/vr/XRInputSourceArray.cpp index 1f6cd9553979..97d0b630638d 100644 --- a/dom/vr/XRInputSourceArray.cpp +++ b/dom/vr/XRInputSourceArray.cpp @@ -96,7 +96,7 @@ void XRInputSourceArray::Update(XRSession* aSession) { if (addInit.mAdded.Length()) { RefPtr event = XRInputSourcesChangeEvent::Constructor( - aSession, NS_LITERAL_STRING("inputsourceschange"), addInit); + aSession, u"inputsourceschange"_ns, addInit); event->SetTrusted(true); aSession->DispatchEvent(*event); @@ -140,8 +140,8 @@ void XRInputSourceArray::DispatchInputSourceRemovedEvent( if (init.mRemoved.Length()) { RefPtr event = - XRInputSourcesChangeEvent::Constructor( - aSession, NS_LITERAL_STRING("inputsourceschange"), init); + XRInputSourcesChangeEvent::Constructor(aSession, + u"inputsourceschange"_ns, init); event->SetTrusted(true); aSession->DispatchEvent(*event); diff --git a/dom/vr/XRPermissionRequest.cpp b/dom/vr/XRPermissionRequest.cpp index 0803e97f05a9..91bfdc687ece 100644 --- a/dom/vr/XRPermissionRequest.cpp +++ b/dom/vr/XRPermissionRequest.cpp @@ -25,8 +25,7 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(XRPermissionRequest, XRPermissionRequest::XRPermissionRequest(nsPIDOMWindowInner* aWindow, uint64_t aWindowId) : ContentPermissionRequestBase(aWindow->GetDoc()->NodePrincipal(), aWindow, - NS_LITERAL_CSTRING("dom.vr"), - NS_LITERAL_CSTRING("xr")), + "dom.vr"_ns, "xr"_ns), mWindowId(aWindowId) { MOZ_ASSERT(aWindow); MOZ_ASSERT(aWindow->GetDoc()); diff --git a/dom/vr/XRSession.cpp b/dom/vr/XRSession.cpp index 1e2dd91e27b5..1661f63dfeaa 100644 --- a/dom/vr/XRSession.cpp +++ b/dom/vr/XRSession.cpp @@ -337,7 +337,7 @@ already_AddRefed XRSession::RequestReferenceSpace( NS_ENSURE_TRUE(!aRv.Failed(), nullptr); if (!mEnabledReferenceSpaceTypes.Contains(aReferenceSpaceType)) { - promise->MaybeRejectWithNotSupportedError(NS_LITERAL_CSTRING( + promise->MaybeRejectWithNotSupportedError(nsLiteralCString( "Requested XRReferenceSpaceType not available for the XRSession.")); return promise.forget(); } @@ -450,7 +450,7 @@ void XRSession::ExitPresentInternal() { init.mCancelable = false; init.mSession = this; RefPtr event = - XRSessionEvent::Constructor(this, NS_LITERAL_STRING("end"), init); + XRSessionEvent::Constructor(this, u"end"_ns, init); event->SetTrusted(true); this->DispatchEvent(*event); diff --git a/dom/vr/XRSystem.cpp b/dom/vr/XRSystem.cpp index 5e38ea46861e..c5133b6b37f6 100644 --- a/dom/vr/XRSystem.cpp +++ b/dom/vr/XRSystem.cpp @@ -476,11 +476,11 @@ void XRSystem::NotifyVRDisplayMounted(uint32_t aDisplayID) {} void XRSystem::NotifyVRDisplayUnmounted(uint32_t aDisplayID) {} void XRSystem::NotifyVRDisplayConnect(uint32_t aDisplayID) { - DispatchTrustedEvent(NS_LITERAL_STRING("devicechange")); + DispatchTrustedEvent(u"devicechange"_ns); } void XRSystem::NotifyVRDisplayDisconnect(uint32_t aDisplayID) { - DispatchTrustedEvent(NS_LITERAL_STRING("devicechange")); + DispatchTrustedEvent(u"devicechange"_ns); } void XRSystem::NotifyVRDisplayPresentChange(uint32_t aDisplayID) {} @@ -631,9 +631,8 @@ XRRequestSessionPermissionRequest::XRRequestSessionPermissionRequest( AllowCallback&& aAllowCallback, AllowAnySiteCallback&& aAllowAnySiteCallback, CancelCallback&& aCancelCallback) - : ContentPermissionRequestBase(aNodePrincipal, aWindow, - NS_LITERAL_CSTRING("dom.xr"), - NS_LITERAL_CSTRING("xr")), + : ContentPermissionRequestBase(aNodePrincipal, aWindow, "dom.xr"_ns, + "xr"_ns), mAllowCallback(std::move(aAllowCallback)), mAllowAnySiteCallback(std::move(aAllowAnySiteCallback)), mCancelCallback(std::move(aCancelCallback)), diff --git a/dom/webauthn/U2FSoftTokenManager.cpp b/dom/webauthn/U2FSoftTokenManager.cpp index 24bbb94ea15d..b50dcdf8c174 100644 --- a/dom/webauthn/U2FSoftTokenManager.cpp +++ b/dom/webauthn/U2FSoftTokenManager.cpp @@ -24,8 +24,7 @@ namespace dom { using namespace mozilla; using mozilla::dom::CreateECParamsForCurve; -const nsCString U2FSoftTokenManager::mSecretNickname = - NS_LITERAL_CSTRING("U2F_NSSTOKEN"); +const nsCString U2FSoftTokenManager::mSecretNickname = "U2F_NSSTOKEN"_ns; namespace { NS_NAMED_LITERAL_CSTRING(kAttestCertSubjectName, "CN=Firefox U2F Soft Token"); diff --git a/dom/webauthn/U2FTokenManager.cpp b/dom/webauthn/U2FTokenManager.cpp index 5a388119743d..49407029ba24 100644 --- a/dom/webauthn/U2FTokenManager.cpp +++ b/dom/webauthn/U2FTokenManager.cpp @@ -366,7 +366,7 @@ void U2FTokenManager::DoRegister(const WebAuthnMakeCredentialInfo& aInfo, U2FTokenManager* mgr = U2FTokenManager::Get(); mgr->MaybeConfirmRegister(tid, aResult); Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_WEBAUTHN_USED, - NS_LITERAL_STRING("U2FRegisterFinish"), 1); + u"U2FRegisterFinish"_ns, 1); Telemetry::AccumulateTimeDelta( Telemetry::WEBAUTHN_CREATE_CREDENTIAL_MS, startTime); }, @@ -375,7 +375,7 @@ void U2FTokenManager::DoRegister(const WebAuthnMakeCredentialInfo& aInfo, U2FTokenManager* mgr = U2FTokenManager::Get(); mgr->MaybeAbortRegister(tid, rv); Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_WEBAUTHN_USED, - NS_LITERAL_STRING("U2FRegisterAbort"), 1); + u"U2FRegisterAbort"_ns, 1); }) ->Track(mRegisterPromise); } @@ -425,7 +425,7 @@ void U2FTokenManager::Sign(PWebAuthnTransactionParent* aTransactionParent, U2FTokenManager* mgr = U2FTokenManager::Get(); mgr->MaybeConfirmSign(tid, aResult); Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_WEBAUTHN_USED, - NS_LITERAL_STRING("U2FSignFinish"), 1); + u"U2FSignFinish"_ns, 1); Telemetry::AccumulateTimeDelta(Telemetry::WEBAUTHN_GET_ASSERTION_MS, startTime); }, @@ -434,7 +434,7 @@ void U2FTokenManager::Sign(PWebAuthnTransactionParent* aTransactionParent, U2FTokenManager* mgr = U2FTokenManager::Get(); mgr->MaybeAbortSign(tid, rv); Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_WEBAUTHN_USED, - NS_LITERAL_STRING("U2FSignAbort"), 1); + u"U2FSignAbort"_ns, 1); }) ->Track(mSignPromise); } diff --git a/dom/webauthn/WebAuthnManager.cpp b/dom/webauthn/WebAuthnManager.cpp index 313740dca0bd..b1505e7fbf03 100644 --- a/dom/webauthn/WebAuthnManager.cpp +++ b/dom/webauthn/WebAuthnManager.cpp @@ -345,8 +345,7 @@ already_AddRefed WebAuthnManager::MakeCredential( } nsAutoCString clientDataJSON; - nsresult srv = AssembleClientData(origin, challenge, - NS_LITERAL_STRING("webauthn.create"), + nsresult srv = AssembleClientData(origin, challenge, u"webauthn.create"_ns, aOptions.mExtensions, clientDataJSON); if (NS_WARN_IF(NS_FAILED(srv))) { promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR); @@ -526,9 +525,8 @@ already_AddRefed WebAuthnManager::GetAssertion( } nsAutoCString clientDataJSON; - nsresult srv = - AssembleClientData(origin, challenge, NS_LITERAL_STRING("webauthn.get"), - aOptions.mExtensions, clientDataJSON); + nsresult srv = AssembleClientData(origin, challenge, u"webauthn.get"_ns, + aOptions.mExtensions, clientDataJSON); if (NS_WARN_IF(NS_FAILED(srv))) { promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR); return promise.forget(); @@ -724,7 +722,7 @@ void WebAuthnManager::FinishMakeCredential( RefPtr credential = new PublicKeyCredential(mParent); credential->SetId(keyHandleBase64Url); - credential->SetType(NS_LITERAL_STRING("public-key")); + credential->SetType(u"public-key"_ns); credential->SetRawId(keyHandleBuf); credential->SetResponse(attestation); @@ -803,7 +801,7 @@ void WebAuthnManager::FinishGetAssertion( RefPtr credential = new PublicKeyCredential(mParent); credential->SetId(credentialBase64Url); - credential->SetType(NS_LITERAL_STRING("public-key")); + credential->SetType(u"public-key"_ns); credential->SetRawId(credentialBuf); credential->SetResponse(assertion); diff --git a/dom/webbrowserpersist/WebBrowserPersistLocalDocument.cpp b/dom/webbrowserpersist/WebBrowserPersistLocalDocument.cpp index 104029b51b50..4d9913eaec9e 100644 --- a/dom/webbrowserpersist/WebBrowserPersistLocalDocument.cpp +++ b/dom/webbrowserpersist/WebBrowserPersistLocalDocument.cpp @@ -140,8 +140,7 @@ WebBrowserPersistLocalDocument::GetContentDisposition(nsAString& aCD) { } nsCOMPtr utils = nsGlobalWindowOuter::Cast(window)->WindowUtils(); - nsresult rv = - utils->GetDocumentMetadata(NS_LITERAL_STRING("content-disposition"), aCD); + nsresult rv = utils->GetDocumentMetadata(u"content-disposition"_ns, aCD); if (NS_WARN_IF(NS_FAILED(rv))) { aCD.SetIsVoid(true); } @@ -660,7 +659,7 @@ nsresult PersistNodeFixup::FixupAnchor(nsINode* aNode) { RefPtr attrMap = element->Attributes(); // Make all anchor links absolute so they point off onto the Internet - nsString attribute(NS_LITERAL_STRING("href")); + nsString attribute(u"href"_ns); RefPtr attr = attrMap->GetNamedItem(attribute); if (attr) { nsString oldValue; @@ -756,21 +755,21 @@ nsresult PersistNodeFixup::FixupXMLStyleSheetLink( nsContentUtils::GetPseudoAttributeValue(data, nsGkAtoms::media, media); nsAutoString newData; - AppendXMLAttr(NS_LITERAL_STRING("href"), aHref, newData); + AppendXMLAttr(u"href"_ns, aHref, newData); if (!title.IsEmpty()) { - AppendXMLAttr(NS_LITERAL_STRING("title"), title, newData); + AppendXMLAttr(u"title"_ns, title, newData); } if (!media.IsEmpty()) { - AppendXMLAttr(NS_LITERAL_STRING("media"), media, newData); + AppendXMLAttr(u"media"_ns, media, newData); } if (!type.IsEmpty()) { - AppendXMLAttr(NS_LITERAL_STRING("type"), type, newData); + AppendXMLAttr(u"type"_ns, type, newData); } if (!charset.IsEmpty()) { - AppendXMLAttr(NS_LITERAL_STRING("charset"), charset, newData); + AppendXMLAttr(u"charset"_ns, charset, newData); } if (!alternate.IsEmpty()) { - AppendXMLAttr(NS_LITERAL_STRING("alternate"), alternate, newData); + AppendXMLAttr(u"alternate"_ns, alternate, newData); } aPI->SetData(newData, IgnoreErrors()); } @@ -831,8 +830,7 @@ PersistNodeFixup::FixupNode(nsINode* aNodeIn, bool* aSerializeCloneKids, nsAutoString commentText; commentText.AssignLiteral(" base "); if (!href.IsEmpty()) { - commentText += - NS_LITERAL_STRING("href=\"") + href + NS_LITERAL_STRING("\" "); + commentText += u"href=\""_ns + href + u"\" "_ns; } *aNodeOut = ownerDoc->CreateComment(commentText).take(); return NS_OK; diff --git a/dom/webbrowserpersist/nsWebBrowserPersist.cpp b/dom/webbrowserpersist/nsWebBrowserPersist.cpp index 1613095bf27e..3a0bf404a68a 100644 --- a/dom/webbrowserpersist/nsWebBrowserPersist.cpp +++ b/dom/webbrowserpersist/nsWebBrowserPersist.cpp @@ -1518,8 +1518,8 @@ nsresult nsWebBrowserPersist::SaveDocumentInternal( dataDirParent->GetLeafName(dirName); nsAutoCString newRelativePathToData; - newRelativePathToData = NS_ConvertUTF16toUTF8(dirName) + - NS_LITERAL_CSTRING("/") + relativePathToData; + newRelativePathToData = + NS_ConvertUTF16toUTF8(dirName) + "/"_ns + relativePathToData; relativePathToData = newRelativePathToData; nsCOMPtr newDataDirParent; @@ -2490,10 +2490,10 @@ nsresult nsWebBrowserPersist::SaveSubframeContent( mWalkStack.AppendElement(std::move(toWalk)); } else { nsContentPolicyType policyType = nsIContentPolicy::TYPE_OTHER; - if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/"))) { + if (StringBeginsWith(contentType, "image/"_ns)) { policyType = nsIContentPolicy::TYPE_IMAGE; - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("audio/")) || - StringBeginsWith(contentType, NS_LITERAL_CSTRING("video/"))) { + } else if (StringBeginsWith(contentType, "audio/"_ns) || + StringBeginsWith(contentType, "video/"_ns)) { policyType = nsIContentPolicy::TYPE_MEDIA; } rv = StoreURI(aURISpec, aParentDocument, policyType); diff --git a/dom/websocket/WebSocket.cpp b/dom/websocket/WebSocket.cpp index caa60d9cd58c..7b1f3c652798 100644 --- a/dom/websocket/WebSocket.cpp +++ b/dom/websocket/WebSocket.cpp @@ -68,10 +68,10 @@ #include "nsProxyRelease.h" #include "nsWeakReference.h" -#define OPEN_EVENT_STRING NS_LITERAL_STRING("open") -#define MESSAGE_EVENT_STRING NS_LITERAL_STRING("message") -#define ERROR_EVENT_STRING NS_LITERAL_STRING("error") -#define CLOSE_EVENT_STRING NS_LITERAL_STRING("close") +#define OPEN_EVENT_STRING u"open"_ns +#define MESSAGE_EVENT_STRING u"message"_ns +#define ERROR_EVENT_STRING u"error"_ns +#define CLOSE_EVENT_STRING u"close"_ns using namespace mozilla::net; @@ -269,9 +269,8 @@ class PrintErrorOnConsoleRunnable final : public WorkerMainThreadRunnable { PrintErrorOnConsoleRunnable(WebSocketImpl* aImpl, const char* aBundleURI, const char* aError, nsTArray&& aFormatStrings) - : WorkerMainThreadRunnable( - aImpl->mWorkerRef->Private(), - NS_LITERAL_CSTRING("WebSocket :: print error on console")), + : WorkerMainThreadRunnable(aImpl->mWorkerRef->Private(), + "WebSocket :: print error on console"_ns), mImpl(aImpl), mBundleURI(aBundleURI), mError(aError), @@ -527,7 +526,7 @@ class DisconnectInternalRunnable final : public WorkerMainThreadRunnable { public: explicit DisconnectInternalRunnable(WebSocketImpl* aImpl) : WorkerMainThreadRunnable(GetCurrentThreadWorkerPrivate(), - NS_LITERAL_CSTRING("WebSocket :: disconnect")), + "WebSocket :: disconnect"_ns), mImpl(aImpl) {} bool MainThreadRun() override { @@ -983,8 +982,7 @@ class InitRunnable final : public WebSocketMainThreadRunnable { nsTArray& aProtocolArray, const nsACString& aScriptFile, uint32_t aScriptLine, uint32_t aScriptColumn) - : WebSocketMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("WebSocket :: init")), + : WebSocketMainThreadRunnable(aWorkerPrivate, "WebSocket :: init"_ns), mImpl(aImpl), mIsServerSide(aIsServerSide), mURL(aURL), @@ -1048,8 +1046,7 @@ class InitRunnable final : public WebSocketMainThreadRunnable { class ConnectRunnable final : public WebSocketMainThreadRunnable { public: ConnectRunnable(WorkerPrivate* aWorkerPrivate, WebSocketImpl* aImpl) - : WebSocketMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("WebSocket :: init")), + : WebSocketMainThreadRunnable(aWorkerPrivate, "WebSocket :: init"_ns), mImpl(aImpl), mConnectionFailed(true) { MOZ_ASSERT(mWorkerPrivate); @@ -1090,9 +1087,8 @@ class AsyncOpenRunnable final : public WebSocketMainThreadRunnable { public: explicit AsyncOpenRunnable(WebSocketImpl* aImpl, UniquePtr aOriginStack) - : WebSocketMainThreadRunnable( - aImpl->mWorkerRef->Private(), - NS_LITERAL_CSTRING("WebSocket :: AsyncOpen")), + : WebSocketMainThreadRunnable(aImpl->mWorkerRef->Private(), + "WebSocket :: AsyncOpen"_ns), mImpl(aImpl), mOriginStack(std::move(aOriginStack)), mErrorCode(NS_OK) { @@ -1595,15 +1591,15 @@ nsresult WebSocketImpl::Init(JSContext* aCx, nsIPrincipal* aLoadingPrincipal, } mSecure = true; - params.AppendElement(NS_LITERAL_STRING("wss")); + params.AppendElement(u"wss"_ns); CSP_LogLocalizedStr("upgradeInsecureRequest", params, EmptyString(), // aSourceFile EmptyString(), // aScriptSample 0, // aLineNumber 0, // aColumnNumber nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("upgradeInsecureRequest"), - mInnerWindowID, mPrivateBrowsing); + "upgradeInsecureRequest"_ns, mInnerWindowID, + mPrivateBrowsing); } // Don't allow https:// to open ws:// diff --git a/dom/workers/MessageEventRunnable.cpp b/dom/workers/MessageEventRunnable.cpp index 3aa997f05ae7..f88f6342add1 100644 --- a/dom/workers/MessageEventRunnable.cpp +++ b/dom/workers/MessageEventRunnable.cpp @@ -97,7 +97,7 @@ bool MessageEventRunnable::DispatchDOMEvent(JSContext* aCx, } RefPtr event = new MessageEvent(aTarget, nullptr, nullptr); - event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), CanBubble::eNo, + event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo, Cancelable::eNo, messageData, EmptyString(), EmptyString(), nullptr, ports); @@ -148,8 +148,8 @@ void MessageEventRunnable::DispatchError(JSContext* aCx, init.mBubbles = false; init.mCancelable = false; - RefPtr event = MessageEvent::Constructor( - aTarget, NS_LITERAL_STRING("messageerror"), init); + RefPtr event = + MessageEvent::Constructor(aTarget, u"messageerror"_ns, init); event->SetTrusted(true); aTarget->DispatchEvent(*event); diff --git a/dom/workers/RuntimeService.cpp b/dom/workers/RuntimeService.cpp index ca50dff90d10..fa4eae22b100 100644 --- a/dom/workers/RuntimeService.cpp +++ b/dom/workers/RuntimeService.cpp @@ -237,9 +237,9 @@ void LoadContextOptions(const char* aPrefName, void* /* aClosure */) { // another callback that will handle this change. if (StringBeginsWith( prefName, - NS_LITERAL_CSTRING(PREF_JS_OPTIONS_PREFIX PREF_MEM_OPTIONS_PREFIX)) || + nsLiteralCString(PREF_JS_OPTIONS_PREFIX PREF_MEM_OPTIONS_PREFIX)) || StringBeginsWith( - prefName, NS_LITERAL_CSTRING( + prefName, nsLiteralCString( PREF_WORKERS_OPTIONS_PREFIX PREF_MEM_OPTIONS_PREFIX))) { return; } @@ -254,39 +254,35 @@ void LoadContextOptions(const char* aPrefName, void* /* aClosure */) { // Context options. JS::ContextOptions contextOptions; contextOptions - .setAsmJS(GetWorkerPref(NS_LITERAL_CSTRING("asmjs"))) + .setAsmJS(GetWorkerPref("asmjs"_ns)) #ifdef FUZZING - .setFuzzing(GetWorkerPref(NS_LITERAL_CSTRING("fuzzing.enabled"))) + .setFuzzing(GetWorkerPref("fuzzing.enabled"_ns)) #endif - .setWasm(GetWorkerPref(NS_LITERAL_CSTRING("wasm"))) + .setWasm(GetWorkerPref("wasm"_ns)) .setWasmForTrustedPrinciples( - GetWorkerPref(NS_LITERAL_CSTRING("wasm_trustedprincipals"))) - .setWasmBaseline( - GetWorkerPref(NS_LITERAL_CSTRING("wasm_baselinejit"))) - .setWasmIon(GetWorkerPref(NS_LITERAL_CSTRING("wasm_ionjit"))) - .setWasmReftypes(GetWorkerPref(NS_LITERAL_CSTRING("wasm_reftypes"))) + GetWorkerPref("wasm_trustedprincipals"_ns)) + .setWasmBaseline(GetWorkerPref("wasm_baselinejit"_ns)) + .setWasmIon(GetWorkerPref("wasm_ionjit"_ns)) + .setWasmReftypes(GetWorkerPref("wasm_reftypes"_ns)) #ifdef ENABLE_WASM_CRANELIFT - .setWasmCranelift( - GetWorkerPref(NS_LITERAL_CSTRING("wasm_cranelift"))) + .setWasmCranelift(GetWorkerPref("wasm_cranelift"_ns)) #endif #ifdef ENABLE_WASM_MULTI_VALUE - .setWasmMultiValue( - GetWorkerPref(NS_LITERAL_CSTRING("wasm_multi_value"))) + .setWasmMultiValue(GetWorkerPref("wasm_multi_value"_ns)) #endif #ifdef ENABLE_WASM_SIMD - .setWasmSimd(GetWorkerPref(NS_LITERAL_CSTRING("wasm_simd"))) + .setWasmSimd(GetWorkerPref("wasm_simd"_ns)) #endif #ifdef ENABLE_WASM_REFTYPES - .setWasmGc(GetWorkerPref(NS_LITERAL_CSTRING("wasm_gc"))) + .setWasmGc(GetWorkerPref("wasm_gc"_ns)) #endif - .setWasmVerbose(GetWorkerPref(NS_LITERAL_CSTRING("wasm_verbose"))) - .setThrowOnAsmJSValidationFailure(GetWorkerPref( - NS_LITERAL_CSTRING("throw_on_asmjs_validation_failure"))) - .setSourcePragmas( - GetWorkerPref(NS_LITERAL_CSTRING("source_pragmas"))) - .setAsyncStack(GetWorkerPref(NS_LITERAL_CSTRING("asyncstack"))) - .setAsyncStackCaptureDebuggeeOnly(GetWorkerPref( - NS_LITERAL_CSTRING("asyncstack_capture_debuggee_only"))); + .setWasmVerbose(GetWorkerPref("wasm_verbose"_ns)) + .setThrowOnAsmJSValidationFailure( + GetWorkerPref("throw_on_asmjs_validation_failure"_ns)) + .setSourcePragmas(GetWorkerPref("source_pragmas"_ns)) + .setAsyncStack(GetWorkerPref("asyncstack"_ns)) + .setAsyncStackCaptureDebuggeeOnly( + GetWorkerPref("asyncstack_capture_debuggee_only"_ns)); nsCOMPtr xr = do_GetService("@mozilla.org/xre/runtime;1"); if (xr) { @@ -314,13 +310,12 @@ void LoadGCZealOptions(const char* /* aPrefName */, void* /* aClosure */) { return; } - int32_t gczeal = GetWorkerPref(NS_LITERAL_CSTRING(PREF_GCZEAL), -1); + int32_t gczeal = GetWorkerPref(nsLiteralCString(PREF_GCZEAL), -1); if (gczeal < 0) { gczeal = 0; } - int32_t frequency = - GetWorkerPref(NS_LITERAL_CSTRING("gcZeal.frequency"), -1); + int32_t frequency = GetWorkerPref("gcZeal.frequency"_ns, -1); if (frequency < 0) { frequency = JS_DEFAULT_ZEAL_FREQ; } @@ -504,9 +499,8 @@ class LogViolationDetailsRunnable final : public WorkerMainThreadRunnable { LogViolationDetailsRunnable(WorkerPrivate* aWorker, const nsString& aFileName, uint32_t aLineNum, uint32_t aColumnNum, const nsAString& aScriptSample) - : WorkerMainThreadRunnable( - aWorker, - NS_LITERAL_CSTRING("RuntimeService :: LogViolationDetails")), + : WorkerMainThreadRunnable(aWorker, + "RuntimeService :: LogViolationDetails"_ns), mFileName(aFileName), mLineNum(aLineNum), mColumnNum(aColumnNum), diff --git a/dom/workers/ScriptLoader.cpp b/dom/workers/ScriptLoader.cpp index cc9b630e5338..e28a5302089f 100644 --- a/dom/workers/ScriptLoader.cpp +++ b/dom/workers/ScriptLoader.cpp @@ -809,7 +809,7 @@ class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed { // We synthesize the result code, but its never exposed to content. RefPtr ir = - new mozilla::dom::InternalResponse(200, NS_LITERAL_CSTRING("OK")); + new mozilla::dom::InternalResponse(200, "OK"_ns); ir->SetBody(aLoadInfo.mCacheReadStream, InternalResponse::UNKNOWN_BODY_SIZE); @@ -1234,15 +1234,14 @@ class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed { return NS_ERROR_NOT_AVAILABLE; } - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy"), tCspHeaderValue); + Unused << httpChannel->GetResponseHeader("content-security-policy"_ns, + tCspHeaderValue); Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy-report-only"), - tCspROHeaderValue); + "content-security-policy-report-only"_ns, tCspROHeaderValue); - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("referrer-policy"), tRPHeaderCValue); + Unused << httpChannel->GetResponseHeader("referrer-policy"_ns, + tRPHeaderCValue); } // May be null. @@ -1255,12 +1254,12 @@ class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed { if (StaticPrefs::dom_worker_script_loader_utf8_parsing_enabled()) { aLoadInfo.InitUTF8Script(); rv = ScriptLoader::ConvertToUTF8( - nullptr, aString, aStringLen, NS_LITERAL_STRING("UTF-8"), parentDoc, + nullptr, aString, aStringLen, u"UTF-8"_ns, parentDoc, aLoadInfo.mScript.mUTF8, aLoadInfo.mScriptLength); } else { aLoadInfo.InitUTF16Script(); rv = ScriptLoader::ConvertToUTF16( - nullptr, aString, aStringLen, NS_LITERAL_STRING("UTF-8"), parentDoc, + nullptr, aString, aStringLen, u"UTF-8"_ns, parentDoc, aLoadInfo.mScript.mUTF16, aLoadInfo.mScriptLength); } if (NS_FAILED(rv)) { @@ -1273,7 +1272,7 @@ class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed { } nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), parentDoc, + nsIScriptError::warningFlag, "DOM"_ns, parentDoc, nsContentUtils::eDOM_PROPERTIES, "EmptyWorkerSourceWarning"); } @@ -1391,12 +1390,12 @@ class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed { if (StaticPrefs::dom_worker_script_loader_utf8_parsing_enabled()) { aLoadInfo.InitUTF8Script(); rv = ScriptLoader::ConvertToUTF8( - nullptr, aString, aStringLen, NS_LITERAL_STRING("UTF-8"), parentDoc, + nullptr, aString, aStringLen, u"UTF-8"_ns, parentDoc, aLoadInfo.mScript.mUTF8, aLoadInfo.mScriptLength); } else { aLoadInfo.InitUTF16Script(); rv = ScriptLoader::ConvertToUTF16( - nullptr, aString, aStringLen, NS_LITERAL_STRING("UTF-8"), parentDoc, + nullptr, aString, aStringLen, u"UTF-8"_ns, parentDoc, aLoadInfo.mScript.mUTF16, aLoadInfo.mScriptLength); } if (NS_SUCCEEDED(rv) && IsMainWorkerScript()) { @@ -1837,16 +1836,14 @@ void CacheScriptLoader::ResolvedCallback(JSContext* aCx, InternalHeaders* headers = response->GetInternalHeaders(); - headers->Get(NS_LITERAL_CSTRING("content-security-policy"), mCSPHeaderValue, - IgnoreErrors()); - headers->Get(NS_LITERAL_CSTRING("content-security-policy-report-only"), + headers->Get("content-security-policy"_ns, mCSPHeaderValue, IgnoreErrors()); + headers->Get("content-security-policy-report-only"_ns, mCSPReportOnlyHeaderValue, IgnoreErrors()); - headers->Get(NS_LITERAL_CSTRING("referrer-policy"), - mReferrerPolicyHeaderValue, IgnoreErrors()); + headers->Get("referrer-policy"_ns, mReferrerPolicyHeaderValue, + IgnoreErrors()); nsAutoCString coepHeader; - headers->Get(NS_LITERAL_CSTRING("cross-origin-embedder-policy"), coepHeader, - IgnoreErrors()); + headers->Get("cross-origin-embedder-policy"_ns, coepHeader, IgnoreErrors()); nsILoadInfo::CrossOriginEmbedderPolicy coep = NS_GetCrossOriginEmbedderPolicyFromHeader(coepHeader); @@ -1948,8 +1945,8 @@ class ChannelGetterRunnable final : public WorkerMainThreadRunnable { public: ChannelGetterRunnable(WorkerPrivate* aParentWorker, const nsAString& aScriptURL, WorkerLoadInfo& aLoadInfo) - : WorkerMainThreadRunnable( - aParentWorker, NS_LITERAL_CSTRING("ScriptLoader :: ChannelGetter")), + : WorkerMainThreadRunnable(aParentWorker, + "ScriptLoader :: ChannelGetter"_ns), mScriptURL(aScriptURL) // ClientInfo should always be present since this should not be called // if parent's status is greater than Running. diff --git a/dom/workers/WorkerCSPEventListener.cpp b/dom/workers/WorkerCSPEventListener.cpp index 2e1ca6abf282..672a7d1548c1 100644 --- a/dom/workers/WorkerCSPEventListener.cpp +++ b/dom/workers/WorkerCSPEventListener.cpp @@ -28,8 +28,8 @@ class WorkerCSPEventRunnable final : public MainThreadWorkerRunnable { RefPtr event = mozilla::dom::SecurityPolicyViolationEvent::Constructor( - aWorkerPrivate->GlobalScope(), - NS_LITERAL_STRING("securitypolicyviolation"), violationEventInit); + aWorkerPrivate->GlobalScope(), u"securitypolicyviolation"_ns, + violationEventInit); event->SetTrusted(true); aWorkerPrivate->GlobalScope()->DispatchEvent(*event); diff --git a/dom/workers/WorkerDebugger.cpp b/dom/workers/WorkerDebugger.cpp index b533ee9ff5fa..7dffab579d9e 100644 --- a/dom/workers/WorkerDebugger.cpp +++ b/dom/workers/WorkerDebugger.cpp @@ -54,9 +54,9 @@ class DebuggerMessageEventRunnable : public WorkerDebuggerRunnable { RefPtr event = new MessageEvent(globalScope, nullptr, nullptr); - event->InitMessageEvent(nullptr, NS_LITERAL_STRING("message"), - CanBubble::eNo, Cancelable::eYes, data, - EmptyString(), EmptyString(), nullptr, + event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo, + Cancelable::eYes, data, EmptyString(), + EmptyString(), nullptr, Sequence>()); event->SetTrusted(true); diff --git a/dom/workers/WorkerError.cpp b/dom/workers/WorkerError.cpp index d253f5e3a9ca..cbf01435b722 100644 --- a/dom/workers/WorkerError.cpp +++ b/dom/workers/WorkerError.cpp @@ -204,8 +204,8 @@ class ReportGenericErrorRunnable final : public WorkerDebuggeeRunnable { RefPtr parentEventTarget = aWorkerPrivate->ParentEventTargetRef(); - RefPtr event = Event::Constructor( - parentEventTarget, NS_LITERAL_STRING("error"), EventInit()); + RefPtr event = + Event::Constructor(parentEventTarget, u"error"_ns, EventInit()); event->SetTrusted(true); parentEventTarget->DispatchEvent(*event); @@ -287,7 +287,7 @@ void WorkerErrorReport::ReportError( if (aTarget) { RefPtr event = - ErrorEvent::Constructor(aTarget, NS_LITERAL_STRING("error"), init); + ErrorEvent::Constructor(aTarget, u"error"_ns, init); event->SetTrusted(true); bool defaultActionEnabled = @@ -340,7 +340,7 @@ void WorkerErrorReport::ReportError( MOZ_ASSERT(globalScope->GetWrapperPreserveColor() == global); RefPtr event = - ErrorEvent::Constructor(aTarget, NS_LITERAL_STRING("error"), init); + ErrorEvent::Constructor(aTarget, u"error"_ns, init); event->SetTrusted(true); if (NS_FAILED(EventDispatcher::DispatchDOMEvent( diff --git a/dom/workers/WorkerLoadInfo.cpp b/dom/workers/WorkerLoadInfo.cpp index 90bb7a7220f0..910d81e203ea 100644 --- a/dom/workers/WorkerLoadInfo.cpp +++ b/dom/workers/WorkerLoadInfo.cpp @@ -308,7 +308,7 @@ bool WorkerLoadInfo::PrincipalURIMatchesScriptURL() { // A system principal must either be a blob URL or a resource JSM. if (mPrincipal->IsSystemPrincipal()) { - if (scheme == NS_LITERAL_CSTRING("blob")) { + if (scheme == "blob"_ns) { return true; } @@ -323,15 +323,14 @@ bool WorkerLoadInfo::PrincipalURIMatchesScriptURL() { // A null principal can occur for a data URL worker script or a blob URL // worker script from a sandboxed iframe. if (mPrincipal->GetIsNullPrincipal()) { - return scheme == NS_LITERAL_CSTRING("data") || - scheme == NS_LITERAL_CSTRING("blob"); + return scheme == "data"_ns || scheme == "blob"_ns; } // The principal for a blob: URL worker script does not have a matching URL. // This is likely a bug in our referer setting logic, but exempt it for now. // This is another reason we should fix bug 1340694 so that referer does not // depend on the principal URI. - if (scheme == NS_LITERAL_CSTRING("blob")) { + if (scheme == "blob"_ns) { return true; } diff --git a/dom/workers/WorkerNavigator.cpp b/dom/workers/WorkerNavigator.cpp index 41693313c2f2..e94c5ee4dc24 100644 --- a/dom/workers/WorkerNavigator.cpp +++ b/dom/workers/WorkerNavigator.cpp @@ -130,8 +130,7 @@ class GetUserAgentRunnable final : public WorkerMainThreadRunnable { public: GetUserAgentRunnable(WorkerPrivate* aWorkerPrivate, nsString& aUA) - : WorkerMainThreadRunnable(aWorkerPrivate, - NS_LITERAL_CSTRING("UserAgent getter")), + : WorkerMainThreadRunnable(aWorkerPrivate, "UserAgent getter"_ns), mUA(aUA) { MOZ_ASSERT(aWorkerPrivate); aWorkerPrivate->AssertIsOnWorkerThread(); diff --git a/dom/workers/WorkerPrivate.cpp b/dom/workers/WorkerPrivate.cpp index 529b32e9e9de..97e3fb5b4db0 100644 --- a/dom/workers/WorkerPrivate.cpp +++ b/dom/workers/WorkerPrivate.cpp @@ -505,9 +505,9 @@ class ReportErrorToConsoleRunnable final : public WorkerRunnable { } // Log a warning to the console. - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), nullptr, - nsContentUtils::eDOM_PROPERTIES, aMessage, aParams); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + nullptr, nsContentUtils::eDOM_PROPERTIES, + aMessage, aParams); } private: @@ -796,7 +796,7 @@ class MemoryPressureRunnable : public WorkerControlRunnable { #ifdef DEBUG static bool StartsWithExplicit(nsACString& s) { - return StringBeginsWith(s, NS_LITERAL_CSTRING("explicit/")); + return StringBeginsWith(s, "explicit/"_ns); } #endif @@ -1022,7 +1022,7 @@ class WorkerJSContextStats final : public JS::RuntimeStats { extras->jsPathPrefix.Assign(mRtPath); extras->jsPathPrefix += nsPrintfCString("zone(0x%p)/", (void*)js::GetRealmZone(aRealm)); - extras->jsPathPrefix += NS_LITERAL_CSTRING("realm(web-worker)/"); + extras->jsPathPrefix += "realm(web-worker)/"_ns; // This should never be used when reporting with workers (hence the "?!"). extras->domPathPrefix.AssignLiteral("explicit/workers/?!/"); @@ -1242,8 +1242,7 @@ WorkerPrivate::MemoryReporter::FinishCollectRunnable::Run() { mHandleReport->Callback( EmptyCString(), path, nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, mPerformanceUserEntries, - NS_LITERAL_CSTRING("Memory used for performance user entries."), - mHandlerData); + "Memory used for performance user entries."_ns, mHandlerData); } if (mPerformanceResourceEntries) { @@ -1252,8 +1251,7 @@ WorkerPrivate::MemoryReporter::FinishCollectRunnable::Run() { mHandleReport->Callback( EmptyCString(), path, nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, mPerformanceResourceEntries, - NS_LITERAL_CSTRING("Memory used for performance resource entries."), - mHandlerData); + "Memory used for performance resource entries."_ns, mHandlerData); } } @@ -2655,8 +2653,8 @@ nsresult WorkerPrivate::GetLoadInfo(JSContext* aCx, nsPIDOMWindowInner* aWindow, NS_ENSURE_SUCCESS(rv, rv); uint32_t perm; - rv = permMgr->TestPermissionFromPrincipal( - loadInfo.mLoadingPrincipal, NS_LITERAL_CSTRING("systemXHR"), &perm); + rv = permMgr->TestPermissionFromPrincipal(loadInfo.mLoadingPrincipal, + "systemXHR"_ns, &perm); NS_ENSURE_SUCCESS(rv, rv); loadInfo.mXHRParamsAllowed = perm == nsIPermissionManager::ALLOW_ACTION; @@ -4815,7 +4813,7 @@ void WorkerPrivate::UpdateLanguagesInternal( RefPtr event = NS_NewDOMEvent(globalScope, nullptr, nullptr); - event->InitEvent(NS_LITERAL_STRING("languagechange"), false, false); + event->InitEvent(u"languagechange"_ns, false, false); event->SetTrusted(true); globalScope->DispatchEvent(*event); @@ -5054,8 +5052,8 @@ bool WorkerPrivate::ConnectMessagePort(JSContext* aCx, return false; } - RefPtr event = MessageEvent::Constructor( - globalObject, NS_LITERAL_STRING("connect"), init); + RefPtr event = + MessageEvent::Constructor(globalObject, u"connect"_ns, init); event->SetTrusted(true); diff --git a/dom/workers/WorkerThread.cpp b/dom/workers/WorkerThread.cpp index dd3aefb28e18..2ffe8c2712ad 100644 --- a/dom/workers/WorkerThread.cpp +++ b/dom/workers/WorkerThread.cpp @@ -91,7 +91,7 @@ SafeRefPtr WorkerThread::Create( const WorkerThreadFriendKey& /* aKey */) { SafeRefPtr thread = MakeSafeRefPtr(ConstructorKey()); - if (NS_FAILED(thread->Init(NS_LITERAL_CSTRING("DOM Worker")))) { + if (NS_FAILED(thread->Init("DOM Worker"_ns))) { NS_WARNING("Failed to create new thread!"); return nullptr; } diff --git a/dom/workers/sharedworkers/SharedWorker.cpp b/dom/workers/sharedworkers/SharedWorker.cpp index a1ccafd46a9f..6a737bc0e0fc 100644 --- a/dom/workers/sharedworkers/SharedWorker.cpp +++ b/dom/workers/sharedworkers/SharedWorker.cpp @@ -386,8 +386,8 @@ void SharedWorker::ErrorPropagation(nsresult aError) { MOZ_ASSERT(mActor); MOZ_ASSERT(NS_FAILED(aError)); - RefPtr errorEvent = new AsyncEventDispatcher( - this, NS_LITERAL_STRING("error"), CanBubble::eNo); + RefPtr errorEvent = + new AsyncEventDispatcher(this, u"error"_ns, CanBubble::eNo); errorEvent->PostDOMEvent(); Close(); diff --git a/dom/workers/sharedworkers/SharedWorkerChild.cpp b/dom/workers/sharedworkers/SharedWorkerChild.cpp index 2b3c3d43f14e..64b91ec75d74 100644 --- a/dom/workers/sharedworkers/SharedWorkerChild.cpp +++ b/dom/workers/sharedworkers/SharedWorkerChild.cpp @@ -89,11 +89,9 @@ IPCResult SharedWorkerChild::RecvError(const ErrorValue& aValue) { errorInit.mLineno = errorData.lineNumber(); errorInit.mColno = errorData.columnNumber(); - event = - ErrorEvent::Constructor(mParent, NS_LITERAL_STRING("error"), errorInit); + event = ErrorEvent::Constructor(mParent, u"error"_ns, errorInit); } else { - event = - Event::Constructor(mParent, NS_LITERAL_STRING("error"), EventInit()); + event = Event::Constructor(mParent, u"error"_ns, EventInit()); } event->SetTrusted(true); diff --git a/dom/worklet/Worklet.cpp b/dom/worklet/Worklet.cpp index 78f80371d05f..69914a0b2092 100644 --- a/dom/worklet/Worklet.cpp +++ b/dom/worklet/Worklet.cpp @@ -226,9 +226,9 @@ class WorkletFetchHandler final : public PromiseNativeHandler, JS::UniqueTwoByteChars scriptTextBuf; size_t scriptTextLength; - nsresult rv = ScriptLoader::ConvertToUTF16( - nullptr, aString, aStringLen, NS_LITERAL_STRING("UTF-8"), nullptr, - scriptTextBuf, scriptTextLength); + nsresult rv = + ScriptLoader::ConvertToUTF16(nullptr, aString, aStringLen, u"UTF-8"_ns, + nullptr, scriptTextBuf, scriptTextLength); if (NS_WARN_IF(NS_FAILED(rv))) { RejectPromises(rv); return NS_OK; diff --git a/dom/worklet/WorkletThread.cpp b/dom/worklet/WorkletThread.cpp index 442dc30a7794..ca6b0b31eeb7 100644 --- a/dom/worklet/WorkletThread.cpp +++ b/dom/worklet/WorkletThread.cpp @@ -265,7 +265,7 @@ WorkletThread::~WorkletThread() = default; already_AddRefed WorkletThread::Create( WorkletImpl* aWorkletImpl) { RefPtr thread = new WorkletThread(aWorkletImpl); - if (NS_WARN_IF(NS_FAILED(thread->Init(NS_LITERAL_CSTRING("DOM Worklet"))))) { + if (NS_WARN_IF(NS_FAILED(thread->Init("DOM Worklet"_ns)))) { return nullptr; } diff --git a/dom/xhr/XMLHttpRequestMainThread.cpp b/dom/xhr/XMLHttpRequestMainThread.cpp index 56bcd294dfd6..11706af17567 100644 --- a/dom/xhr/XMLHttpRequestMainThread.cpp +++ b/dom/xhr/XMLHttpRequestMainThread.cpp @@ -120,23 +120,18 @@ const int32_t XML_HTTP_REQUEST_MAX_CONTENT_LENGTH_PREALLOCATE = namespace { const nsLiteralString ProgressEventTypeStrings[] = { - NS_LITERAL_STRING("loadstart"), NS_LITERAL_STRING("progress"), - NS_LITERAL_STRING("error"), NS_LITERAL_STRING("abort"), - NS_LITERAL_STRING("timeout"), NS_LITERAL_STRING("load"), - NS_LITERAL_STRING("loadend")}; + u"loadstart"_ns, u"progress"_ns, u"error"_ns, u"abort"_ns, + u"timeout"_ns, u"load"_ns, u"loadend"_ns}; static_assert(MOZ_ARRAY_LENGTH(ProgressEventTypeStrings) == size_t(XMLHttpRequestMainThread::ProgressEventType::ENUM_MAX), "Mismatched lengths for ProgressEventTypeStrings and " "ProgressEventType enums"); -const nsString kLiteralString_readystatechange = - NS_LITERAL_STRING("readystatechange"); -const nsString kLiteralString_xmlhttprequest = - NS_LITERAL_STRING("xmlhttprequest"); -const nsString kLiteralString_DOMContentLoaded = - NS_LITERAL_STRING("DOMContentLoaded"); -const nsCString kLiteralString_charset = NS_LITERAL_CSTRING("charset"); -const nsCString kLiteralString_UTF_8 = NS_LITERAL_CSTRING("UTF-8"); +const nsString kLiteralString_readystatechange = u"readystatechange"_ns; +const nsString kLiteralString_xmlhttprequest = u"xmlhttprequest"_ns; +const nsString kLiteralString_DOMContentLoaded = u"DOMContentLoaded"_ns; +const nsCString kLiteralString_charset = "charset"_ns; +const nsCString kLiteralString_UTF_8 = "UTF-8"_ns; } // namespace #define NS_PROGRESS_EVENT_INTERVAL 50 @@ -286,7 +281,7 @@ void XMLHttpRequestMainThread::InitParameters(bool aAnon, bool aSystem) { uint32_t permission; nsresult rv = permMgr->TestPermissionFromPrincipal( - principal, NS_LITERAL_CSTRING("systemXHR"), &permission); + principal, "systemXHR"_ns, &permission); if (NS_FAILED(rv) || permission != nsIPermissionManager::ALLOW_ACTION) { SetParameters(aAnon, false); return; @@ -426,9 +421,9 @@ static void LogMessage( if (aWindow) { doc = aWindow->GetExtantDoc(); } - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), doc, - nsContentUtils::eDOM_PROPERTIES, aWarning, aParams); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, doc, + nsContentUtils::eDOM_PROPERTIES, aWarning, + aParams); } Document* XMLHttpRequestMainThread::GetResponseXML(ErrorResult& aRv) { @@ -1068,8 +1063,8 @@ bool XMLHttpRequestMainThread::IsSafeHeader( nsAutoCString headerVal; // The "Access-Control-Expose-Headers" header contains a comma separated // list of method names. - Unused << aHttpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Expose-Headers"), headerVal); + Unused << aHttpChannel->GetResponseHeader("Access-Control-Expose-Headers"_ns, + headerVal); nsCCharSeparatedTokenizer exposeTokens(headerVal, ','); bool isSafe = false; while (exposeTokens.hasMoreTokens()) { @@ -1874,7 +1869,7 @@ XMLHttpRequestMainThread::OnStartRequest(nsIRequest* request) { nsAutoCString type; channel->GetContentType(type); if (type.EqualsLiteral(UNKNOWN_CONTENT_TYPE)) { - channel->SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM)); + channel->SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM)); } DetectCharset(); @@ -1908,8 +1903,7 @@ XMLHttpRequestMainThread::OnStartRequest(nsIRequest* request) { if (NS_FAILED(rv)) { mIsMappedArrayBuffer = false; } else { - channel->SetContentType( - NS_LITERAL_CSTRING("application/mem-mapped")); + channel->SetContentType("application/mem-mapped"_ns); } } } @@ -2453,7 +2447,7 @@ nsresult XMLHttpRequestMainThread::CreateChannel() { // Set the initiator type nsCOMPtr timedChannel(do_QueryInterface(httpChannel)); if (timedChannel) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("xmlhttprequest")); + timedChannel->SetInitiatorType(u"xmlhttprequest"_ns); } } @@ -2542,7 +2536,7 @@ nsresult XMLHttpRequestMainThread::InitiateFetch( if (httpChannel) { // If the user hasn't overridden the Accept header, set it to */* per spec. if (!mAuthorRequestHeaders.Has("accept")) { - mAuthorRequestHeaders.Set("accept", NS_LITERAL_CSTRING("*/*")); + mAuthorRequestHeaders.Set("accept", "*/*"_ns); } mAuthorRequestHeaders.ApplyToChannel(httpChannel, false); @@ -2767,7 +2761,7 @@ void XMLHttpRequestMainThread::EnsureChannelContentType() { if (NS_FAILED(mChannel->GetContentType(contentType)) || contentType.IsEmpty() || contentType.EqualsLiteral(UNKNOWN_CONTENT_TYPE)) { - mChannel->SetContentType(NS_LITERAL_CSTRING("text/xml")); + mChannel->SetContentType("text/xml"_ns); } } diff --git a/dom/xhr/XMLHttpRequestWorker.cpp b/dom/xhr/XMLHttpRequestWorker.cpp index e2b19bb16d45..28a0917784bf 100644 --- a/dom/xhr/XMLHttpRequestWorker.cpp +++ b/dom/xhr/XMLHttpRequestWorker.cpp @@ -203,7 +203,7 @@ class WorkerThreadProxySyncRunnable : public WorkerMainThreadRunnable { public: WorkerThreadProxySyncRunnable(WorkerPrivate* aWorkerPrivate, Proxy* aProxy) - : WorkerMainThreadRunnable(aWorkerPrivate, NS_LITERAL_CSTRING("XHR")), + : WorkerMainThreadRunnable(aWorkerPrivate, "XHR"_ns), mProxy(aProxy), mErrorCode(NS_OK) { MOZ_ASSERT(aWorkerPrivate); @@ -1487,13 +1487,12 @@ void XMLHttpRequestWorker::MaybeDispatchPrematureAbortEvents(ErrorResult& aRv) { if (mProxy->mSeenUploadLoadStart) { MOZ_ASSERT(mUpload); - DispatchPrematureAbortEvent(mUpload, NS_LITERAL_STRING("abort"), true, aRv); + DispatchPrematureAbortEvent(mUpload, u"abort"_ns, true, aRv); if (aRv.Failed()) { return; } - DispatchPrematureAbortEvent(mUpload, NS_LITERAL_STRING("loadend"), true, - aRv); + DispatchPrematureAbortEvent(mUpload, u"loadend"_ns, true, aRv); if (aRv.Failed()) { return; } @@ -1510,19 +1509,18 @@ void XMLHttpRequestWorker::MaybeDispatchPrematureAbortEvents(ErrorResult& aRv) { if (mProxy->mSeenLoadStart) { if (isStateChanged) { - DispatchPrematureAbortEvent(this, NS_LITERAL_STRING("readystatechange"), - false, aRv); + DispatchPrematureAbortEvent(this, u"readystatechange"_ns, false, aRv); if (aRv.Failed()) { return; } } - DispatchPrematureAbortEvent(this, NS_LITERAL_STRING("abort"), false, aRv); + DispatchPrematureAbortEvent(this, u"abort"_ns, false, aRv); if (aRv.Failed()) { return; } - DispatchPrematureAbortEvent(this, NS_LITERAL_STRING("loadend"), false, aRv); + DispatchPrematureAbortEvent(this, u"loadend"_ns, false, aRv); if (aRv.Failed()) { return; } @@ -1615,9 +1613,9 @@ void XMLHttpRequestWorker::SendInternal(const BodyExtractorBase* aBody, return; } - blobImpl = StreamBlobImpl::Create( - uploadStream.forget(), NS_ConvertUTF8toUTF16(defaultContentType), - size_u64, NS_LITERAL_STRING("StreamBlobImpl")); + blobImpl = StreamBlobImpl::Create(uploadStream.forget(), + NS_ConvertUTF8toUTF16(defaultContentType), + size_u64, u"StreamBlobImpl"_ns); MOZ_ASSERT(blobImpl); } diff --git a/dom/xml/nsXMLPrettyPrinter.cpp b/dom/xml/nsXMLPrettyPrinter.cpp index 88a063676591..2a7ad013ef95 100644 --- a/dom/xml/nsXMLPrettyPrinter.cpp +++ b/dom/xml/nsXMLPrettyPrinter.cpp @@ -57,9 +57,8 @@ nsresult nsXMLPrettyPrinter::PrettyPrint(Document* aDocument, // Load the XSLT nsCOMPtr xslUri; - rv = NS_NewURI( - getter_AddRefs(xslUri), - NS_LITERAL_CSTRING("chrome://global/content/xml/XMLPrettyPrint.xsl")); + rv = NS_NewURI(getter_AddRefs(xslUri), + "chrome://global/content/xml/XMLPrettyPrint.xsl"_ns); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr xslDocument; diff --git a/dom/xslt/xpath/txCoreFunctionCall.cpp b/dom/xslt/xpath/txCoreFunctionCall.cpp index f43502f053bf..9585944e9e43 100644 --- a/dom/xslt/xpath/txCoreFunctionCall.cpp +++ b/dom/xslt/xpath/txCoreFunctionCall.cpp @@ -587,8 +587,7 @@ nsresult txCoreFunctionCall::evaluate(txIEvalContext* aContext, } } - aContext->receiveError(NS_LITERAL_STRING("Internal error"), - NS_ERROR_UNEXPECTED); + aContext->receiveError(u"Internal error"_ns, NS_ERROR_UNEXPECTED); return NS_ERROR_UNEXPECTED; } diff --git a/dom/xslt/xpath/txErrorExpr.cpp b/dom/xslt/xpath/txErrorExpr.cpp index 437a63715ade..806b32425902 100644 --- a/dom/xslt/xpath/txErrorExpr.cpp +++ b/dom/xslt/xpath/txErrorExpr.cpp @@ -12,7 +12,7 @@ nsresult txErrorExpr::evaluate(txIEvalContext* aContext, txAExprResult** aResult) { *aResult = nullptr; - nsAutoString err(NS_LITERAL_STRING("Invalid expression evaluated")); + nsAutoString err(u"Invalid expression evaluated"_ns); #ifdef TX_TO_STRING err.AppendLiteral(": "); toString(err); diff --git a/dom/xslt/xpath/txExprParser.cpp b/dom/xslt/xpath/txExprParser.cpp index a1f9bbd3a579..4f7e2fc90f7e 100644 --- a/dom/xslt/xpath/txExprParser.cpp +++ b/dom/xslt/xpath/txExprParser.cpp @@ -436,8 +436,7 @@ nsresult txExprParser::createFunctionCall(txExprLexer& lexer, rv = parseParameters(0, lexer, aContext); NS_ENSURE_SUCCESS(rv, rv); - *aResult = new txLiteralExpr(tok->Value() + - NS_LITERAL_STRING(" not implemented.")); + *aResult = new txLiteralExpr(tok->Value() + u" not implemented."_ns); return NS_OK; } diff --git a/dom/xslt/xpath/txForwardContext.cpp b/dom/xslt/xpath/txForwardContext.cpp index d5b80ecb6e77..44b53fefbcc5 100644 --- a/dom/xslt/xpath/txForwardContext.cpp +++ b/dom/xslt/xpath/txForwardContext.cpp @@ -41,7 +41,7 @@ txResultRecycler* txForwardContext::recycler() { void txForwardContext::receiveError(const nsAString& aMsg, nsresult aRes) { NS_ASSERTION(mInner, "mInner is null!!!"); #ifdef DEBUG - nsAutoString error(NS_LITERAL_STRING("forwarded error: ")); + nsAutoString error(u"forwarded error: "_ns); error.Append(aMsg); mInner->receiveError(error, aRes); #else diff --git a/dom/xslt/xpath/txFunctionCall.cpp b/dom/xslt/xpath/txFunctionCall.cpp index 88b44b46e52a..0e58d8cc7a6f 100644 --- a/dom/xslt/xpath/txFunctionCall.cpp +++ b/dom/xslt/xpath/txFunctionCall.cpp @@ -46,7 +46,7 @@ nsresult FunctionCall::evaluateToNodeSet(Expr* aExpr, txIEvalContext* aContext, NS_ENSURE_SUCCESS(rv, rv); if (exprRes->getResultType() != txAExprResult::NODESET) { - aContext->receiveError(NS_LITERAL_STRING("NodeSet expected as argument"), + aContext->receiveError(u"NodeSet expected as argument"_ns, NS_ERROR_XSLT_NODESET_EXPECTED); return NS_ERROR_XSLT_NODESET_EXPECTED; } @@ -61,8 +61,7 @@ bool FunctionCall::requireParams(int32_t aParamCountMin, int32_t aParamCountMax, txIEvalContext* aContext) { int32_t argc = mParams.Length(); if (argc < aParamCountMin || (aParamCountMax > -1 && argc > aParamCountMax)) { - nsAutoString err( - NS_LITERAL_STRING("invalid number of parameters for function")); + nsAutoString err(u"invalid number of parameters for function"_ns); #ifdef TX_TO_STRING err.AppendLiteral(": "); toString(err); diff --git a/dom/xslt/xpath/txNodeSetContext.cpp b/dom/xslt/xpath/txNodeSetContext.cpp index 636d29511f6d..7565e1254533 100644 --- a/dom/xslt/xpath/txNodeSetContext.cpp +++ b/dom/xslt/xpath/txNodeSetContext.cpp @@ -42,7 +42,7 @@ txResultRecycler* txNodeSetContext::recycler() { void txNodeSetContext::receiveError(const nsAString& aMsg, nsresult aRes) { NS_ASSERTION(mInner, "mInner is null!!!"); #ifdef DEBUG - nsAutoString error(NS_LITERAL_STRING("forwarded error: ")); + nsAutoString error(u"forwarded error: "_ns); error.Append(aMsg); mInner->receiveError(error, aRes); #else diff --git a/dom/xslt/xpath/txSingleNodeContext.h b/dom/xslt/xpath/txSingleNodeContext.h index b1cf4d7aacfd..80b0680a2dd8 100644 --- a/dom/xslt/xpath/txSingleNodeContext.h +++ b/dom/xslt/xpath/txSingleNodeContext.h @@ -42,7 +42,7 @@ class txSingleNodeContext : public txIEvalContext { void receiveError(const nsAString& aMsg, nsresult aRes) override { NS_ASSERTION(mInner, "mInner is null!!!"); #ifdef DEBUG - nsAutoString error(NS_LITERAL_STRING("forwarded error: ")); + nsAutoString error(u"forwarded error: "_ns); error.Append(aMsg); mInner->receiveError(error, aRes); #else diff --git a/dom/xslt/xslt/txEXSLTFunctions.cpp b/dom/xslt/xslt/txEXSLTFunctions.cpp index 05c5e580372a..aecba54c1ee0 100644 --- a/dom/xslt/xslt/txEXSLTFunctions.cpp +++ b/dom/xslt/xslt/txEXSLTFunctions.cpp @@ -616,8 +616,7 @@ nsresult txEXSLTFunctionCall::evaluate(txIEvalContext* aContext, return NS_OK; } default: { - aContext->receiveError(NS_LITERAL_STRING("Internal error"), - NS_ERROR_UNEXPECTED); + aContext->receiveError(u"Internal error"_ns, NS_ERROR_UNEXPECTED); return NS_ERROR_UNEXPECTED; } } @@ -721,8 +720,7 @@ nsresult txEXSLTRegExFunctionCall::evaluate(txIEvalContext* aContext, return NS_OK; } default: { - aContext->receiveError(NS_LITERAL_STRING("Internal error"), - NS_ERROR_UNEXPECTED); + aContext->receiveError(u"Internal error"_ns, NS_ERROR_UNEXPECTED); return NS_ERROR_UNEXPECTED; } } diff --git a/dom/xslt/xslt/txExecutionState.cpp b/dom/xslt/xslt/txExecutionState.cpp index a4e7609dfc39..4a4d17689907 100644 --- a/dom/xslt/xslt/txExecutionState.cpp +++ b/dom/xslt/xslt/txExecutionState.cpp @@ -137,8 +137,7 @@ nsresult txExecutionState::init( // The actual value here doesn't really matter since noone should use this // value. But lets put something errorlike in just in case - mGlobalVarPlaceholderValue = - new StringResult(NS_LITERAL_STRING("Error"), nullptr); + mGlobalVarPlaceholderValue = new StringResult(u"Error"_ns, nullptr); // Initiate first instruction. This has to be done last since findTemplate // might use us. @@ -394,8 +393,7 @@ const txXPathNode* txExecutionState::retrieveDocument(const nsAString& aUri) { getter_Transfers(entry->mDocument)); if (entry->LoadingFailed()) { - receiveError(NS_LITERAL_STRING("Couldn't load document '") + aUri + - NS_LITERAL_STRING("': ") + errMsg, + receiveError(u"Couldn't load document '"_ns + aUri + u"': "_ns + errMsg, entry->mLoadResult); } } diff --git a/dom/xslt/xslt/txFormatNumberFunctionCall.cpp b/dom/xslt/xslt/txFormatNumberFunctionCall.cpp index 386104146260..eee810ef1649 100644 --- a/dom/xslt/xslt/txFormatNumberFunctionCall.cpp +++ b/dom/xslt/xslt/txFormatNumberFunctionCall.cpp @@ -14,8 +14,7 @@ #include "prdtoa.h" -#define INVALID_PARAM_VALUE \ - NS_LITERAL_STRING("invalid parameter value for function") +#define INVALID_PARAM_VALUE u"invalid parameter value for function"_ns const char16_t txFormatNumberFunctionCall::FORMAT_QUOTE = '\''; @@ -74,7 +73,7 @@ nsresult txFormatNumberFunctionCall::evaluate(txIEvalContext* aContext, txDecimalFormat* format = mStylesheet->getDecimalFormat(formatName); if (!format) { - nsAutoString err(NS_LITERAL_STRING("unknown decimal format")); + nsAutoString err(u"unknown decimal format"_ns); #ifdef TX_TO_STRING err.AppendLiteral(" for: "); toString(err); @@ -385,7 +384,7 @@ void txFormatNumberFunctionCall::appendName(nsAString& aDest) { */ txDecimalFormat::txDecimalFormat() - : mInfinity(NS_LITERAL_STRING("Infinity")), mNaN(NS_LITERAL_STRING("NaN")) { + : mInfinity(u"Infinity"_ns), mNaN(u"NaN"_ns) { mDecimalSeparator = '.'; mGroupingSeparator = ','; mMinusSign = '-'; diff --git a/dom/xslt/xslt/txInstructions.cpp b/dom/xslt/xslt/txInstructions.cpp index cf49baf224a7..ef1b1576874b 100644 --- a/dom/xslt/xslt/txInstructions.cpp +++ b/dom/xslt/xslt/txInstructions.cpp @@ -451,7 +451,7 @@ nsresult txMessage::execute(txExecutionState& aEs) { nsCOMPtr consoleSvc = do_GetService("@mozilla.org/consoleservice;1"); if (consoleSvc) { - nsAutoString logString(NS_LITERAL_STRING("xsl:message - ")); + nsAutoString logString(u"xsl:message - "_ns); logString.Append(handler->mValue); consoleSvc->LogStringMessage(logString.get()); } diff --git a/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp b/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp index 20ab20b40eb3..c6ce4a5b090b 100644 --- a/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp +++ b/dom/xslt/xslt/txMozillaStylesheetCompiler.cpp @@ -405,7 +405,7 @@ nsresult txCompileObserver::startLoad(nsIURI* aUri, NS_ENSURE_SUCCESS(rv, rv); - channel->SetContentType(NS_LITERAL_CSTRING("text/xml")); + channel->SetContentType("text/xml"_ns); nsCOMPtr httpChannel(do_QueryInterface(channel)); if (httpChannel) { diff --git a/dom/xslt/xslt/txMozillaTextOutput.cpp b/dom/xslt/xslt/txMozillaTextOutput.cpp index 62633e29681b..3aa9dae60450 100644 --- a/dom/xslt/xslt/txMozillaTextOutput.cpp +++ b/dom/xslt/xslt/txMozillaTextOutput.cpp @@ -195,9 +195,8 @@ nsresult txMozillaTextOutput::createResultDocument(Document* aSourceDocument, mTextParent = std::move(textParent); } - rv = mTextParent->AsElement()->SetAttr( - kNameSpaceID_None, nsGkAtoms::id, - NS_LITERAL_STRING("transformiixResult"), false); + rv = mTextParent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::id, + u"transformiixResult"_ns, false); NS_ENSURE_SUCCESS(rv, rv); rv = body->AppendChildTo(mTextParent, false); diff --git a/dom/xslt/xslt/txMozillaXMLOutput.cpp b/dom/xslt/xslt/txMozillaXMLOutput.cpp index d1ddd9b9276d..bb7d09b2d4a7 100644 --- a/dom/xslt/xslt/txMozillaXMLOutput.cpp +++ b/dom/xslt/xslt/txMozillaXMLOutput.cpp @@ -651,7 +651,7 @@ nsresult txMozillaXMLOutput::startHTMLElement(nsIContent* aElement, NS_ENSURE_SUCCESS(rv, rv); rv = meta->SetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, - NS_LITERAL_STRING("Content-Type"), false); + u"Content-Type"_ns, false); NS_ENSURE_SUCCESS(rv, rv); nsAutoString metacontent; @@ -764,9 +764,9 @@ nsresult txMozillaXMLOutput::createResultDocument(const nsAString& aName, if (!mOutputFormat.mMediaType.IsEmpty()) { mDocument->SetContentType(mOutputFormat.mMediaType); } else if (mOutputFormat.mMethod == eHTMLOutput) { - mDocument->SetContentType(NS_LITERAL_STRING("text/html")); + mDocument->SetContentType(u"text/html"_ns); } else { - mDocument->SetContentType(NS_LITERAL_STRING("application/xml")); + mDocument->SetContentType(u"application/xml"_ns); } if (mOutputFormat.mMethod == eXMLOutput && diff --git a/dom/xslt/xslt/txMozillaXSLTProcessor.cpp b/dom/xslt/xslt/txMozillaXSLTProcessor.cpp index 1b22b1caf029..24eddd0cb7d4 100644 --- a/dom/xslt/xslt/txMozillaXSLTProcessor.cpp +++ b/dom/xslt/xslt/txMozillaXSLTProcessor.cpp @@ -983,8 +983,8 @@ void txMozillaXSLTProcessor::notifyError() { ElementCreationOptionsOrString options; options.SetAsString(); - nsCOMPtr element = document->CreateElementNS( - ns, NS_LITERAL_STRING("parsererror"), options, rv); + nsCOMPtr element = + document->CreateElementNS(ns, u"parsererror"_ns, options, rv); if (rv.Failed()) { return; } @@ -1005,8 +1005,8 @@ void txMozillaXSLTProcessor::notifyError() { ElementCreationOptionsOrString options; options.SetAsString(); - nsCOMPtr sourceElement = document->CreateElementNS( - ns, NS_LITERAL_STRING("sourcetext"), options, rv); + nsCOMPtr sourceElement = + document->CreateElementNS(ns, u"sourcetext"_ns, options, rv); if (rv.Failed()) { return; } diff --git a/dom/xslt/xslt/txUnknownHandler.cpp b/dom/xslt/xslt/txUnknownHandler.cpp index 59ac34b76513..8007b9181eba 100644 --- a/dom/xslt/xslt/txUnknownHandler.cpp +++ b/dom/xslt/xslt/txUnknownHandler.cpp @@ -134,9 +134,9 @@ nsresult txUnknownHandler::startElement(nsAtom* aPrefix, NS_ASSERTION(mEs->mResultHandler == this, "We're leaking mEs->mResultHandler."); - bool htmlRoot = aNsID == kNameSpaceID_None && !aPrefix && - aLocalName.Equals(NS_LITERAL_STRING("html"), - nsCaseInsensitiveStringComparator); + bool htmlRoot = + aNsID == kNameSpaceID_None && !aPrefix && + aLocalName.Equals(u"html"_ns, nsCaseInsensitiveStringComparator); nsresult rv = createHandlerAndFlush(htmlRoot, aLocalName, aNsID); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/dom/xslt/xslt/txXSLTEnvironmentFunctionCall.cpp b/dom/xslt/xslt/txXSLTEnvironmentFunctionCall.cpp index 4510840b8770..621388b3833f 100644 --- a/dom/xslt/xslt/txXSLTEnvironmentFunctionCall.cpp +++ b/dom/xslt/xslt/txXSLTEnvironmentFunctionCall.cpp @@ -34,13 +34,12 @@ nsresult txXSLTEnvironmentFunctionCall::evaluate(txIEvalContext* aContext, return aContext->recycler()->getNumberResult(1.0, aResult); } if (qname.mLocalName == nsGkAtoms::vendor) { - return aContext->recycler()->getStringResult( - NS_LITERAL_STRING("Transformiix"), aResult); + return aContext->recycler()->getStringResult(u"Transformiix"_ns, + aResult); } if (qname.mLocalName == nsGkAtoms::vendorUrl) { return aContext->recycler()->getStringResult( - NS_LITERAL_STRING("http://www.mozilla.org/projects/xslt/"), - aResult); + u"http://www.mozilla.org/projects/xslt/"_ns, aResult); } } aContext->recycler()->getEmptyStringResult(aResult); diff --git a/dom/xslt/xslt/txXSLTNumber.cpp b/dom/xslt/xslt/txXSLTNumber.cpp index 78b22888348c..f48ca5f7d518 100644 --- a/dom/xslt/xslt/txXSLTNumber.cpp +++ b/dom/xslt/xslt/txXSLTNumber.cpp @@ -335,8 +335,8 @@ nsresult txXSLTNumber::getCounters(Expr* aGroupSize, Expr* aGroupSeparator, // If there are no formatting tokens we need to create a default one. if (formatPos == formatLen) { txFormattedCounter* defaultCounter; - rv = txFormattedCounter::getCounterFor(NS_LITERAL_STRING("1"), groupSize, - groupSeparator, defaultCounter); + rv = txFormattedCounter::getCounterFor(u"1"_ns, groupSize, groupSeparator, + defaultCounter); NS_ENSURE_SUCCESS(rv, rv); defaultCounter->mSeparator.Assign('.'); diff --git a/dom/xul/ChromeObserver.cpp b/dom/xul/ChromeObserver.cpp index ac160b9fea6a..37eeb261f6f1 100644 --- a/dom/xul/ChromeObserver.cpp +++ b/dom/xul/ChromeObserver.cpp @@ -110,8 +110,8 @@ void ChromeObserver::UpdateBrightTitlebarForeground() { mainWidget->SetUseBrightTitlebarForeground( mDocument->GetDocumentLWTheme() == Document::Doc_Theme_Bright || mDocument->GetRootElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::brighttitlebarforeground, - NS_LITERAL_STRING("true"), eCaseMatters)); + kNameSpaceID_None, nsGkAtoms::brighttitlebarforeground, u"true"_ns, + eCaseMatters)); } } @@ -172,7 +172,7 @@ void ChromeObserver::AttributeChanged(dom::Element* aElement, if (value) { // Hide chrome if needed if (aName == nsGkAtoms::hidechrome) { - HideWindowChrome(value->Equals(NS_LITERAL_STRING("true"), eCaseMatters)); + HideWindowChrome(value->Equals(u"true"_ns, eCaseMatters)); } else if (aName == nsGkAtoms::chromemargin) { SetChromeMargins(value); } else if (aName == nsGkAtoms::windowtype && aElement->IsXULElement()) { @@ -184,10 +184,9 @@ void ChromeObserver::AttributeChanged(dom::Element* aElement, else if (aName == nsGkAtoms::title) { mDocument->NotifyPossibleTitleChange(false); } else if (aName == nsGkAtoms::drawintitlebar) { - SetDrawsInTitlebar( - value->Equals(NS_LITERAL_STRING("true"), eCaseMatters)); + SetDrawsInTitlebar(value->Equals(u"true"_ns, eCaseMatters)); } else if (aName == nsGkAtoms::drawtitle) { - SetDrawsTitle(value->Equals(NS_LITERAL_STRING("true"), eCaseMatters)); + SetDrawsTitle(value->Equals(u"true"_ns, eCaseMatters)); } else if (aName == nsGkAtoms::localedir) { // if the localedir changed on the root element, reset the document // direction diff --git a/dom/xul/XULFrameElement.cpp b/dom/xul/XULFrameElement.cpp index 93a11df8462b..00139e35895a 100644 --- a/dom/xul/XULFrameElement.cpp +++ b/dom/xul/XULFrameElement.cpp @@ -100,7 +100,7 @@ void XULFrameElement::LoadSrc() { return; } - (new AsyncEventDispatcher(this, NS_LITERAL_STRING("XULFrameLoaderCreated"), + (new AsyncEventDispatcher(this, u"XULFrameLoaderCreated"_ns, CanBubble::eYes)) ->RunDOMEventWhenSafe(); } diff --git a/dom/xul/XULTooltipElement.cpp b/dom/xul/XULTooltipElement.cpp index 59d96b0300e1..5669fe76fbb2 100644 --- a/dom/xul/XULTooltipElement.cpp +++ b/dom/xul/XULTooltipElement.cpp @@ -35,9 +35,8 @@ nsresult XULTooltipElement::Init() { dom::NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); description->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("tooltip-label"), false); - description->SetAttr(kNameSpaceID_None, nsGkAtoms::flex, - NS_LITERAL_STRING("true"), false); + u"tooltip-label"_ns, false); + description->SetAttr(kNameSpaceID_None, nsGkAtoms::flex, u"true"_ns, false); ErrorResult error; AppendChild(*description, error); diff --git a/dom/xul/nsXULContentSink.cpp b/dom/xul/nsXULContentSink.cpp index 80c4bc62d394..bdcf6b432b86 100644 --- a/dom/xul/nsXULContentSink.cpp +++ b/dom/xul/nsXULContentSink.cpp @@ -708,11 +708,10 @@ nsresult XULContentSinkImpl::OpenScript(const char16_t** aAttributes, if (NS_SUCCEEDED(rv)) { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING( - "Versioned JavaScripts are no longer supported. " - "Please remove the version parameter."), - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("XUL Document"), - nullptr, mDocumentURL, EmptyString(), aLineNumber); + u"Versioned JavaScripts are no longer supported. " + "Please remove the version parameter."_ns, + nsIScriptError::errorFlag, "XUL Document"_ns, nullptr, + mDocumentURL, EmptyString(), aLineNumber); isJavaScript = false; } else if (rv != NS_ERROR_INVALID_ARG) { return rv; diff --git a/dom/xul/nsXULElement.cpp b/dom/xul/nsXULElement.cpp index d54445851b04..49542ff85c09 100644 --- a/dom/xul/nsXULElement.cpp +++ b/dom/xul/nsXULElement.cpp @@ -107,9 +107,9 @@ nsXULElement::~nsXULElement() = default; void nsXULElement::MaybeUpdatePrivateLifetime() { if (AttrValueIs(kNameSpaceID_None, nsGkAtoms::windowtype, - NS_LITERAL_STRING("navigator:browser"), eCaseMatters) || + u"navigator:browser"_ns, eCaseMatters) || AttrValueIs(kNameSpaceID_None, nsGkAtoms::windowtype, - NS_LITERAL_STRING("navigator:geckoview"), eCaseMatters)) { + u"navigator:geckoview"_ns, eCaseMatters)) { return; } @@ -1080,10 +1080,10 @@ nsresult nsXULElement::AddPopupListener(nsAtom* aName) { SetFlags(listenerFlag); if (isContext) { - manager->AddEventListenerByType(listener, NS_LITERAL_STRING("contextmenu"), + manager->AddEventListenerByType(listener, u"contextmenu"_ns, TrustedEventsAtSystemGroupBubble()); } else { - manager->AddEventListenerByType(listener, NS_LITERAL_STRING("mousedown"), + manager->AddEventListenerByType(listener, u"mousedown"_ns, TrustedEventsAtSystemGroupBubble()); } return NS_OK; diff --git a/dom/xul/nsXULElement.h b/dom/xul/nsXULElement.h index 01b041b04deb..31cf42501ac9 100644 --- a/dom/xul/nsXULElement.h +++ b/dom/xul/nsXULElement.h @@ -371,12 +371,11 @@ class nsXULElement : public nsStyledElement { SetAttr(aName, aValue, aError); } bool GetXULBoolAttr(nsAtom* aName) const { - return AttrValueIs(kNameSpaceID_None, aName, NS_LITERAL_STRING("true"), - eCaseMatters); + return AttrValueIs(kNameSpaceID_None, aName, u"true"_ns, eCaseMatters); } void SetXULBoolAttr(nsAtom* aName, bool aValue) { if (aValue) { - SetAttr(kNameSpaceID_None, aName, NS_LITERAL_STRING("true"), true); + SetAttr(kNameSpaceID_None, aName, u"true"_ns, true); } else { UnsetAttr(kNameSpaceID_None, aName, true); } diff --git a/dom/xul/nsXULPrototypeCache.cpp b/dom/xul/nsXULPrototypeCache.cpp index 949ecdda7eb8..8807ba9084ac 100644 --- a/dom/xul/nsXULPrototypeCache.cpp +++ b/dom/xul/nsXULPrototypeCache.cpp @@ -353,8 +353,7 @@ nsresult nsXULPrototypeCache::BeginCaching(nsIURI* aURI) { nsAutoCString path; aURI->GetPathQueryRef(path); - if (!(StringEndsWith(path, NS_LITERAL_CSTRING(".xul")) || - StringEndsWith(path, NS_LITERAL_CSTRING(".xhtml")))) { + if (!(StringEndsWith(path, ".xul"_ns) || StringEndsWith(path, ".xhtml"_ns))) { return NS_ERROR_NOT_AVAILABLE; } @@ -501,7 +500,7 @@ void nsXULPrototypeCache::CollectMemoryReports( size_t other = mallocSizeOf(sInstance); #define REPORT_SIZE(_path, _amount, _desc) \ - ReportSize(_path, _amount, NS_LITERAL_CSTRING(_desc), aHandleReport, aData) + ReportSize(_path, _amount, nsLiteralCString(_desc), aHandleReport, aData) other += sInstance->mPrototypeTable.ShallowSizeOfExcludingThis(mallocSizeOf); // TODO Report content in mPrototypeTable? @@ -526,7 +525,7 @@ void nsXULPrototypeCache::CollectMemoryReports( other += sInstance->mInputStreamTable.ShallowSizeOfExcludingThis(mallocSizeOf); - REPORT_SIZE(NS_LITERAL_CSTRING("other"), other, + REPORT_SIZE("other"_ns, other, "Memory used by " "the instance and tables of the XUL prototype cache."); diff --git a/dom/xul/nsXULSortService.cpp b/dom/xul/nsXULSortService.cpp index 91a6b09fc23f..22bb76ed3fc0 100644 --- a/dom/xul/nsXULSortService.cpp +++ b/dom/xul/nsXULSortService.cpp @@ -81,7 +81,7 @@ static void SetSortColumnHints(nsIContent* content, child->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::sort, value); if (value == sortResource) { child->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::sortActive, - NS_LITERAL_STRING("true"), true); + u"true"_ns, true); child->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::sortDirection, sortDirection, true); diff --git a/editor/composer/nsEditingSession.cpp b/editor/composer/nsEditingSession.cpp index 7c487e607659..d6f39494c60b 100644 --- a/editor/composer/nsEditingSession.cpp +++ b/editor/composer/nsEditingSession.cpp @@ -926,7 +926,7 @@ void nsEditingSession::TimerCallback(nsITimer* aTimer, void* aClosure) { LoadURIOptions loadURIOptions; loadURIOptions.mTriggeringPrincipal = nsContentUtils::GetSystemPrincipal(); - webNav->LoadURI(NS_LITERAL_STRING("about:blank"), loadURIOptions); + webNav->LoadURI(u"about:blank"_ns, loadURIOptions); } } } diff --git a/editor/libeditor/CSSEditUtils.cpp b/editor/libeditor/CSSEditUtils.cpp index 9a34f30ee628..6a22c4947a89 100644 --- a/editor/libeditor/CSSEditUtils.cpp +++ b/editor/libeditor/CSSEditUtils.cpp @@ -407,7 +407,7 @@ nsresult CSSEditUtils::SetCSSPropertyPixels(Element& aElement, int32_t aIntValue) { nsAutoString s; s.AppendInt(aIntValue); - nsresult rv = SetCSSProperty(aElement, aProperty, s + NS_LITERAL_STRING("px"), + nsresult rv = SetCSSProperty(aElement, aProperty, s + u"px"_ns, /* suppress txn */ false); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "CSSEditUtils::SetCSSProperty() failed"); @@ -1067,7 +1067,7 @@ bool CSSEditUtils::IsCSSEquivalentToHTMLInlineStyleSetInternal( } } } else if (nsGkAtoms::tt == aHTMLProperty) { - isSet = StringBeginsWith(aValue, NS_LITERAL_STRING("monospace")); + isSet = StringBeginsWith(aValue, u"monospace"_ns); } else if (nsGkAtoms::font == aHTMLProperty && aAttribute && aAttribute == nsGkAtoms::face) { if (!htmlValueString.IsEmpty()) { diff --git a/editor/libeditor/ChangeStyleTransaction.cpp b/editor/libeditor/ChangeStyleTransaction.cpp index 2fad8e8c8473..e31d588a2dbc 100644 --- a/editor/libeditor/ChangeStyleTransaction.cpp +++ b/editor/libeditor/ChangeStyleTransaction.cpp @@ -173,7 +173,7 @@ NS_IMETHODIMP ChangeStyleTransaction::DoTransaction() { nsAutoString returnString; if (multiple) { // Let's remove only the value we have to remove and not the others - RemoveValueFromListOfValues(values, NS_LITERAL_STRING("none")); + RemoveValueFromListOfValues(values, u"none"_ns); RemoveValueFromListOfValues(values, mValue); if (values.IsEmpty()) { ErrorResult error; diff --git a/editor/libeditor/EditorBase.cpp b/editor/libeditor/EditorBase.cpp index 37312694b67f..dd2b2441cbcc 100644 --- a/editor/libeditor/EditorBase.cpp +++ b/editor/libeditor/EditorBase.cpp @@ -4552,8 +4552,7 @@ nsresult EditorBase::ToggleTextDirectionAsAction(nsIPrincipal* aPrincipal) { // but not canceled. TextDirection newDirection = IsRightToLeft() ? TextDirection::eLTR : TextDirection::eRTL; - editActionData.SetData(IsRightToLeft() ? NS_LITERAL_STRING("ltr") - : NS_LITERAL_STRING("rtl")); + editActionData.SetData(IsRightToLeft() ? u"ltr"_ns : u"rtl"_ns); // FYI: Oddly, Chrome does not dispatch beforeinput event in this case but // dispatches input event. @@ -4591,9 +4590,8 @@ void EditorBase::SwitchTextDirectionTo(TextDirection aTextDirection) { return; } - editActionData.SetData(aTextDirection == TextDirection::eLTR - ? NS_LITERAL_STRING("ltr") - : NS_LITERAL_STRING("rtl")); + editActionData.SetData(aTextDirection == TextDirection::eLTR ? u"ltr"_ns + : u"rtl"_ns); // FYI: Oddly, Chrome does not dispatch beforeinput event in this case but // dispatches input event. @@ -4629,7 +4627,7 @@ nsresult EditorBase::SetTextDirectionTo(TextDirection aTextDirection) { mFlags &= ~nsIEditor::eEditorRightToLeft; mFlags |= nsIEditor::eEditorLeftToRight; nsresult rv = rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, - NS_LITERAL_STRING("ltr"), true); + u"ltr"_ns, true); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Element::SetAttr(nsGkAtoms::dir, ltr) failed"); return rv; @@ -4640,7 +4638,7 @@ nsresult EditorBase::SetTextDirectionTo(TextDirection aTextDirection) { mFlags |= nsIEditor::eEditorRightToLeft; mFlags &= ~nsIEditor::eEditorLeftToRight; nsresult rv = rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::dir, - NS_LITERAL_STRING("rtl"), true); + u"rtl"_ns, true); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Element::SetAttr(nsGkAtoms::dir, rtl) failed"); return rv; diff --git a/editor/libeditor/EditorEventListener.cpp b/editor/libeditor/EditorEventListener.cpp index 1f4720759f81..0236d236c54b 100644 --- a/editor/libeditor/EditorEventListener.cpp +++ b/editor/libeditor/EditorEventListener.cpp @@ -151,47 +151,45 @@ nsresult EditorEventListener::InstallToEditor() { #ifdef HANDLE_NATIVE_TEXT_DIRECTION_SWITCH eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupBubble()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupBubble()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); #endif eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupBubble()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("dragenter"), TrustedEventsAtSystemGroupBubble()); + this, u"dragenter"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("dragover"), TrustedEventsAtSystemGroupBubble()); + this, u"dragover"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("dragexit"), TrustedEventsAtSystemGroupBubble()); + this, u"dragexit"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("drop"), TrustedEventsAtSystemGroupBubble()); + this, u"drop"_ns, TrustedEventsAtSystemGroupBubble()); // XXX We should add the mouse event listeners as system event group. // E.g., web applications cannot prevent middle mouse paste by // preventDefault() of click event at bubble phase. // However, if we do so, all click handlers in any frames and frontend // code need to check if it's editable. It makes easier create new bugs. - eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mousedown"), TrustedEventsAtCapture()); - eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mouseup"), TrustedEventsAtCapture()); - eventListenerManager->AddEventListenerByType(this, NS_LITERAL_STRING("click"), + eventListenerManager->AddEventListenerByType(this, u"mousedown"_ns, + TrustedEventsAtCapture()); + eventListenerManager->AddEventListenerByType(this, u"mouseup"_ns, + TrustedEventsAtCapture()); + eventListenerManager->AddEventListenerByType(this, u"click"_ns, TrustedEventsAtCapture()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("auxclick"), TrustedEventsAtSystemGroupCapture()); + this, u"auxclick"_ns, TrustedEventsAtSystemGroupCapture()); // Focus event doesn't bubble so adding the listener to capturing phase as // system event group. eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("blur"), TrustedEventsAtSystemGroupCapture()); + this, u"blur"_ns, TrustedEventsAtSystemGroupCapture()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("focus"), TrustedEventsAtSystemGroupCapture()); + this, u"focus"_ns, TrustedEventsAtSystemGroupCapture()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("text"), TrustedEventsAtSystemGroupBubble()); + this, u"text"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("compositionstart"), - TrustedEventsAtSystemGroupBubble()); + this, u"compositionstart"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("compositionend"), - TrustedEventsAtSystemGroupBubble()); + this, u"compositionend"_ns, TrustedEventsAtSystemGroupBubble()); return NS_OK; } @@ -236,40 +234,38 @@ void EditorEventListener::UninstallFromEditor() { #ifdef HANDLE_NATIVE_TEXT_DIRECTION_SWITCH eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keydown"), TrustedEventsAtSystemGroupBubble()); + this, u"keydown"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keyup"), TrustedEventsAtSystemGroupBubble()); + this, u"keyup"_ns, TrustedEventsAtSystemGroupBubble()); #endif eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("keypress"), TrustedEventsAtSystemGroupBubble()); - eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("dragenter"), TrustedEventsAtSystemGroupBubble()); - eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("dragover"), TrustedEventsAtSystemGroupBubble()); - eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("dragexit"), TrustedEventsAtSystemGroupBubble()); + this, u"keypress"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("drop"), TrustedEventsAtSystemGroupBubble()); + this, u"dragenter"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mousedown"), TrustedEventsAtCapture()); + this, u"dragover"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mouseup"), TrustedEventsAtCapture()); + this, u"dragexit"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("click"), TrustedEventsAtCapture()); + this, u"drop"_ns, TrustedEventsAtSystemGroupBubble()); + eventListenerManager->RemoveEventListenerByType(this, u"mousedown"_ns, + TrustedEventsAtCapture()); + eventListenerManager->RemoveEventListenerByType(this, u"mouseup"_ns, + TrustedEventsAtCapture()); + eventListenerManager->RemoveEventListenerByType(this, u"click"_ns, + TrustedEventsAtCapture()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("auxclick"), TrustedEventsAtSystemGroupCapture()); + this, u"auxclick"_ns, TrustedEventsAtSystemGroupCapture()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("blur"), TrustedEventsAtSystemGroupCapture()); + this, u"blur"_ns, TrustedEventsAtSystemGroupCapture()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("focus"), TrustedEventsAtSystemGroupCapture()); + this, u"focus"_ns, TrustedEventsAtSystemGroupCapture()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("text"), TrustedEventsAtSystemGroupBubble()); + this, u"text"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("compositionstart"), - TrustedEventsAtSystemGroupBubble()); + this, u"compositionstart"_ns, TrustedEventsAtSystemGroupBubble()); eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("compositionend"), - TrustedEventsAtSystemGroupBubble()); + this, u"compositionend"_ns, TrustedEventsAtSystemGroupBubble()); } PresShell* EditorEventListener::GetPresShell() const { diff --git a/editor/libeditor/HTMLAbsPositionEditor.cpp b/editor/libeditor/HTMLAbsPositionEditor.cpp index 73c0c2fef7b5..4e02ec2df146 100644 --- a/editor/libeditor/HTMLAbsPositionEditor.cpp +++ b/editor/libeditor/HTMLAbsPositionEditor.cpp @@ -252,7 +252,7 @@ bool HTMLEditor::CreateGrabberInternal(nsIContent& aParentContent) { } mGrabber = CreateAnonymousElement(nsGkAtoms::span, aParentContent, - NS_LITERAL_STRING("mozGrabber"), false); + u"mozGrabber"_ns, false); // mGrabber may be destroyed during creation due to there may be // mutation event listener. @@ -266,8 +266,7 @@ bool HTMLEditor::CreateGrabberInternal(nsIContent& aParentContent) { EventListenerManager* eventListenerManager = mGrabber->GetOrCreateListenerManager(); eventListenerManager->AddEventListenerByType( - mEventListener, NS_LITERAL_STRING("mousedown"), - TrustedEventsAtSystemGroupBubble()); + mEventListener, u"mousedown"_ns, TrustedEventsAtSystemGroupBubble()); MOZ_ASSERT(mGrabber); return true; } @@ -597,7 +596,7 @@ nsresult HTMLEditor::SetPositionToAbsolute(Element& aElement) { "HTMLEditor::GetElementOrigin() failed, but ignored"); rvIgnored = mCSSEditUtils->SetCSSProperty(aElement, *nsGkAtoms::position, - NS_LITERAL_STRING("absolute")); + u"absolute"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored), "CSSEditUtils::SetCSSProperty(nsGkAtoms::position, " "absolute) failed, but ignored"); diff --git a/editor/libeditor/HTMLAnonymousNodeEditor.cpp b/editor/libeditor/HTMLAnonymousNodeEditor.cpp index acc6c95e87d7..5c4eebe0b39b 100644 --- a/editor/libeditor/HTMLAnonymousNodeEditor.cpp +++ b/editor/libeditor/HTMLAnonymousNodeEditor.cpp @@ -151,7 +151,7 @@ ManualNACPtr HTMLEditor::CreateAnonymousElement(nsAtom* aTag, // add the "hidden" class if needed if (aIsCreatedHidden) { nsresult rv = newElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("hidden"), true); + u"hidden"_ns, true); if (NS_FAILED(rv)) { NS_WARNING("Element::SetAttr(nsGkAtoms::_class, hidden) failed"); return nullptr; @@ -534,21 +534,16 @@ nsresult HTMLEditor::GetPositionAndDimensions(Element& aElement, int32_t& aX, return NS_ERROR_FAILURE; } - aBorderLeft = GetCSSFloatValue(computedDOMStyle, - NS_LITERAL_CSTRING("border-left-width")); - aBorderTop = GetCSSFloatValue(computedDOMStyle, - NS_LITERAL_CSTRING("border-top-width")); - aMarginLeft = - GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("margin-left")); - aMarginTop = - GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("margin-top")); - - aX = GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("left")) + - aMarginLeft + aBorderLeft; - aY = GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("top")) + - aMarginTop + aBorderTop; - aW = GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("width")); - aH = GetCSSFloatValue(computedDOMStyle, NS_LITERAL_CSTRING("height")); + aBorderLeft = GetCSSFloatValue(computedDOMStyle, "border-left-width"_ns); + aBorderTop = GetCSSFloatValue(computedDOMStyle, "border-top-width"_ns); + aMarginLeft = GetCSSFloatValue(computedDOMStyle, "margin-left"_ns); + aMarginTop = GetCSSFloatValue(computedDOMStyle, "margin-top"_ns); + + aX = GetCSSFloatValue(computedDOMStyle, "left"_ns) + aMarginLeft + + aBorderLeft; + aY = GetCSSFloatValue(computedDOMStyle, "top"_ns) + aMarginTop + aBorderTop; + aW = GetCSSFloatValue(computedDOMStyle, "width"_ns); + aH = GetCSSFloatValue(computedDOMStyle, "height"_ns); } else { mResizedObjectIsAbsolutelyPositioned = false; RefPtr htmlElement = diff --git a/editor/libeditor/HTMLEditUtils.cpp b/editor/libeditor/HTMLEditUtils.cpp index 19ab51e4e2cd..3bc6f53688e7 100644 --- a/editor/libeditor/HTMLEditUtils.cpp +++ b/editor/libeditor/HTMLEditUtils.cpp @@ -256,8 +256,7 @@ bool HTMLEditUtils::IsMozDiv(nsINode* aNode) { MOZ_ASSERT(aNode); return aNode->IsHTMLElement(nsGkAtoms::div) && aNode->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("_moz"), - eIgnoreCase); + u"_moz"_ns, eIgnoreCase); } /** @@ -269,14 +268,14 @@ bool HTMLEditUtils::IsMailCite(nsINode* aNode) { // don't ask me why, but our html mailcites are id'd by "type=cite"... if (aNode->IsElement() && aNode->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("cite"), eIgnoreCase)) { + u"cite"_ns, eIgnoreCase)) { return true; } // ... but our plaintext mailcites by "_moz_quote=true". go figure. if (aNode->IsElement() && aNode->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::mozquote, - NS_LITERAL_STRING("true"), eIgnoreCase)) { + u"true"_ns, eIgnoreCase)) { return true; } diff --git a/editor/libeditor/HTMLEditor.cpp b/editor/libeditor/HTMLEditor.cpp index 00d46f68d1c3..150084c9c97e 100644 --- a/editor/libeditor/HTMLEditor.cpp +++ b/editor/libeditor/HTMLEditor.cpp @@ -766,7 +766,7 @@ nsresult HTMLEditor::HandleKeyPressEvent(WidgetKeyboardEvent* aKeyboardEvent) { return NS_OK; } aKeyboardEvent->PreventDefault(); - nsresult rv = OnInputText(NS_LITERAL_STRING("\t")); + nsresult rv = OnInputText(u"\t"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "TextEditor::OnInputText(\\t) failed"); return EditorBase::ToGenericNSResult(rv); @@ -935,7 +935,7 @@ NS_IMETHODIMP HTMLEditor::UpdateBaseURL() { // Look for an HTML tag RefPtr baseElementList = - document->GetElementsByTagName(NS_LITERAL_STRING("base")); + document->GetElementsByTagName(u"base"_ns); // If no base tag, then set baseURL to the document's URL. This is very // important, else relative URLs for links and images are wrong @@ -1221,7 +1221,7 @@ nsresult HTMLEditor::ReplaceHeadContentsWithSourceWithTransaction( } RefPtr headElementList = - document->GetElementsByTagName(NS_LITERAL_STRING("head")); + document->GetElementsByTagName(u"head"_ns); if (NS_WARN_IF(!headElementList)) { return NS_ERROR_FAILURE; } @@ -1237,12 +1237,10 @@ nsresult HTMLEditor::ReplaceHeadContentsWithSourceWithTransaction( nsAutoString inputString(aSourceToInsert); // Windows linebreaks: Map CRLF to LF: - inputString.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), - NS_LITERAL_STRING("\n")); + inputString.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns); // Mac linebreaks: Map any remaining CR to LF: - inputString.ReplaceSubstring(NS_LITERAL_STRING("\r"), - NS_LITERAL_STRING("\n")); + inputString.ReplaceSubstring(u"\r"_ns, u"\n"_ns); AutoPlaceholderBatch treatAsOneTransaction(*this); @@ -1316,15 +1314,15 @@ NS_IMETHODIMP HTMLEditor::RebuildDocumentFromSource( nsReadingIterator endbody; aSourceString.BeginReading(beginbody); aSourceString.EndReading(endbody); - bool foundbody = CaseInsensitiveFindInReadable(NS_LITERAL_STRING(" beginhead; nsReadingIterator endhead; aSourceString.BeginReading(beginhead); aSourceString.EndReading(endhead); - bool foundhead = CaseInsensitiveFindInReadable(NS_LITERAL_STRING(" beginbody.get()) { foundhead = false; @@ -1337,7 +1335,7 @@ NS_IMETHODIMP HTMLEditor::RebuildDocumentFromSource( // Find the index after "" bool foundclosehead = CaseInsensitiveFindInReadable( - NS_LITERAL_STRING(""), beginclosehead, endclosehead); + u""_ns, beginclosehead, endclosehead); // a valid close head appears after a found head if (foundhead && beginhead.get() > beginclosehead.get()) { foundclosehead = false; @@ -1483,7 +1481,7 @@ NS_IMETHODIMP HTMLEditor::RebuildDocumentFromSource( nsReadingIterator beginclosebody = beginbody; nsReadingIterator endclosebody; aSourceString.EndReading(endclosebody); - if (!FindInReadable(NS_LITERAL_STRING(">"), beginclosebody, endclosebody)) { + if (!FindInReadable(u">"_ns, beginclosebody, endclosebody)) { NS_WARNING("'>' was not found"); return NS_ERROR_FAILURE; } @@ -2826,39 +2824,35 @@ already_AddRefed HTMLEditor::CreateElementWithDefaults( // Mark the new element dirty, so it will be formatted // XXX Don't we need to check the error result of setting _moz_dirty attr? IgnoredErrorResult ignoredError; - newElement->SetAttribute(NS_LITERAL_STRING("_moz_dirty"), EmptyString(), - ignoredError); + newElement->SetAttribute(u"_moz_dirty"_ns, EmptyString(), ignoredError); NS_WARNING_ASSERTION(!ignoredError.Failed(), "Element::SetAttribute(_moz_dirty) failed, but ignored"); ignoredError.SuppressException(); // Set default values for new elements if (realTagName == nsGkAtoms::table) { - newElement->SetAttr(nsGkAtoms::cellpadding, NS_LITERAL_STRING("2"), - ignoredError); + newElement->SetAttr(nsGkAtoms::cellpadding, u"2"_ns, ignoredError); if (ignoredError.Failed()) { NS_WARNING("Element::SetAttr(nsGkAtoms::cellpadding, 2) failed"); return nullptr; } ignoredError.SuppressException(); - newElement->SetAttr(nsGkAtoms::cellspacing, NS_LITERAL_STRING("2"), - ignoredError); + newElement->SetAttr(nsGkAtoms::cellspacing, u"2"_ns, ignoredError); if (ignoredError.Failed()) { NS_WARNING("Element::SetAttr(nsGkAtoms::cellspacing, 2) failed"); return nullptr; } ignoredError.SuppressException(); - newElement->SetAttr(nsGkAtoms::border, NS_LITERAL_STRING("1"), - ignoredError); + newElement->SetAttr(nsGkAtoms::border, u"1"_ns, ignoredError); if (ignoredError.Failed()) { NS_WARNING("Element::SetAttr(nsGkAtoms::border, 1) failed"); return nullptr; } } else if (realTagName == nsGkAtoms::td) { nsresult rv = SetAttributeOrEquivalent(newElement, nsGkAtoms::valign, - NS_LITERAL_STRING("top"), true); + u"top"_ns, true); if (NS_FAILED(rv)) { NS_WARNING( "HTMLEditor::SetAttributeOrEquivalent(nsGkAtoms::valign, top) " diff --git a/editor/libeditor/HTMLEditorCommands.cpp b/editor/libeditor/HTMLEditorCommands.cpp index 87c50db7a232..ae49060f50fd 100644 --- a/editor/libeditor/HTMLEditorCommands.cpp +++ b/editor/libeditor/HTMLEditorCommands.cpp @@ -557,7 +557,7 @@ nsresult ParagraphStateCommand::GetCurrentState( aParams.SetBool(STATE_MIXED, state.IsMixed()); if (NS_WARN_IF(!state.GetFirstParagraphStateAtSelection())) { // XXX This is odd behavior, we should fix this later. - aParams.SetCString(STATE_ATTRIBUTE, NS_LITERAL_CSTRING("x")); + aParams.SetCString(STATE_ATTRIBUTE, "x"_ns); } else { nsCString paragraphState; // Don't use `nsAutoCString` for avoiding copy. state.GetFirstParagraphStateAtSelection()->ToUTF8String(paragraphState); @@ -918,8 +918,8 @@ nsresult AbsolutePositioningCommand::GetCurrentState( RefPtr container = aHTMLEditor->GetAbsolutelyPositionedSelectionContainer(); aParams.SetBool(STATE_MIXED, false); - aParams.SetCString(STATE_ATTRIBUTE, container ? NS_LITERAL_CSTRING("absolute") - : EmptyCString()); + aParams.SetCString(STATE_ATTRIBUTE, + container ? "absolute"_ns : EmptyCString()); return NS_OK; } diff --git a/editor/libeditor/HTMLEditorDataTransfer.cpp b/editor/libeditor/HTMLEditorDataTransfer.cpp index 9a2d985e65ae..52bc84801719 100644 --- a/editor/libeditor/HTMLEditorDataTransfer.cpp +++ b/editor/libeditor/HTMLEditorDataTransfer.cpp @@ -1020,7 +1020,7 @@ nsresult HTMLEditor::ParseCFHTML(nsCString& aCfhtml, char16_t** aStuffToPaste, // create context string nsAutoCString contextUTF8( Substring(aCfhtml, startHTML, startFragment - startHTML) + - NS_LITERAL_CSTRING("") + + ""_ns + Substring(aCfhtml, endFragment, endHTML - endFragment)); // validate startFragment @@ -1204,10 +1204,10 @@ nsresult HTMLEditor::BlobReader::OnResult(const nsACString& aResult) { nsresult HTMLEditor::BlobReader::OnError(const nsAString& aError) { AutoTArray error; error.AppendElement(aError); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Editor"), - mPointToInsert.GetContainer()->OwnerDoc(), - nsContentUtils::eDOM_PROPERTIES, "EditorFileDropFailed", error); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "Editor"_ns, + mPointToInsert.GetContainer()->OwnerDoc(), + nsContentUtils::eDOM_PROPERTIES, + "EditorFileDropFailed", error); return NS_OK; } @@ -1292,15 +1292,13 @@ nsresult HTMLEditor::SlurpBlob(Blob* aBlob, nsPIDOMWindowOuter* aWindow, RefPtr eventListener = new SlurpBlobEventListener(aBlobReader); - nsresult rv = - reader->AddEventListener(NS_LITERAL_STRING("load"), eventListener, false); + nsresult rv = reader->AddEventListener(u"load"_ns, eventListener, false); if (NS_FAILED(rv)) { NS_WARNING("FileReader::AddEventListener(load) failed"); return rv; } - rv = reader->AddEventListener(NS_LITERAL_STRING("error"), eventListener, - false); + rv = reader->AddEventListener(u"error"_ns, eventListener, false); if (NS_FAILED(rv)) { NS_WARNING("FileReader::AddEventListener(error) failed"); return rv; @@ -2103,7 +2101,7 @@ nsresult HTMLEditor::PasteAsQuotationAsAction(int32_t aClipboardType, return NS_ERROR_FAILURE; } DebugOnly rvIgnored = newBlockquoteElement->SetAttr( - kNameSpaceID_None, nsGkAtoms::type, NS_LITERAL_STRING("cite"), true); + kNameSpaceID_None, nsGkAtoms::type, u"cite"_ns, true); if (NS_WARN_IF(Destroyed())) { return EditorBase::ToGenericNSResult(NS_ERROR_EDITOR_DESTROYED); } @@ -2504,9 +2502,8 @@ nsresult HTMLEditor::InsertAsPlaintextQuotation(const nsAString& aQuotedText, // but we'll fall through and try to insert the text anyway. if (newSpanElement) { // Add an attribute on the pre node so we'll know it's a quotation. - DebugOnly rvIgnored = - newSpanElement->SetAttr(kNameSpaceID_None, nsGkAtoms::mozquote, - NS_LITERAL_STRING("true"), true); + DebugOnly rvIgnored = newSpanElement->SetAttr( + kNameSpaceID_None, nsGkAtoms::mozquote, u"true"_ns, true); NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::mozquote, true) failed"); // Allow wrapping on spans so long lines get wrapped to the screen. @@ -2514,16 +2511,16 @@ nsresult HTMLEditor::InsertAsPlaintextQuotation(const nsAString& aQuotedText, if (parentNode && parentNode->IsHTMLElement(nsGkAtoms::body)) { DebugOnly rvIgnored = newSpanElement->SetAttr( kNameSpaceID_None, nsGkAtoms::style, - NS_LITERAL_STRING( - "white-space: pre-wrap; display: block; width: 98vw;"), + nsLiteralString( + u"white-space: pre-wrap; display: block; width: 98vw;"), true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::style) failed, but ignored"); } else { - DebugOnly rvIgnored = newSpanElement->SetAttr( - kNameSpaceID_None, nsGkAtoms::style, - NS_LITERAL_STRING("white-space: pre-wrap;"), true); + DebugOnly rvIgnored = + newSpanElement->SetAttr(kNameSpaceID_None, nsGkAtoms::style, + u"white-space: pre-wrap;"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::style) failed, but ignored"); @@ -2751,7 +2748,7 @@ nsresult HTMLEditor::InsertAsCitedQuotationInternal( // Try to set type=cite. Ignore it if this fails. DebugOnly rvIgnored = newBlockquoteElement->SetAttr( - kNameSpaceID_None, nsGkAtoms::type, NS_LITERAL_STRING("cite"), true); + kNameSpaceID_None, nsGkAtoms::type, u"cite"_ns, true); if (NS_WARN_IF(Destroyed())) { return NS_ERROR_EDITOR_DESTROYED; } diff --git a/editor/libeditor/HTMLEditorDocumentCommands.cpp b/editor/libeditor/HTMLEditorDocumentCommands.cpp index dc665d66e227..d4023bf2c83e 100644 --- a/editor/libeditor/HTMLEditorDocumentCommands.cpp +++ b/editor/libeditor/HTMLEditorDocumentCommands.cpp @@ -244,22 +244,20 @@ nsresult SetDocumentStateCommand::GetCommandStateParams( switch (htmlEditor->GetDefaultParagraphSeparator()) { case ParagraphSeparator::div: { DebugOnly rv = - aParams.SetCString(STATE_ATTRIBUTE, NS_LITERAL_CSTRING("div")); + aParams.SetCString(STATE_ATTRIBUTE, "div"_ns); NS_WARNING_ASSERTION( NS_SUCCEEDED(rv), "Failed to set command params to return \"div\""); return NS_OK; } case ParagraphSeparator::p: { - DebugOnly rv = - aParams.SetCString(STATE_ATTRIBUTE, NS_LITERAL_CSTRING("p")); + DebugOnly rv = aParams.SetCString(STATE_ATTRIBUTE, "p"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to set command params to return \"p\""); return NS_OK; } case ParagraphSeparator::br: { - DebugOnly rv = - aParams.SetCString(STATE_ATTRIBUTE, NS_LITERAL_CSTRING("br")); + DebugOnly rv = aParams.SetCString(STATE_ATTRIBUTE, "br"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to set command params to return \"br\""); return NS_OK; diff --git a/editor/libeditor/HTMLEditorEventListener.cpp b/editor/libeditor/HTMLEditorEventListener.cpp index 654f27d09fb5..c126774e53d8 100644 --- a/editor/libeditor/HTMLEditorEventListener.cpp +++ b/editor/libeditor/HTMLEditorEventListener.cpp @@ -157,8 +157,7 @@ nsresult HTMLEditorEventListener::ListenToMouseMoveEventForResizersOrGrabber( if (aListen) { eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("mousemove"), - TrustedEventsAtSystemGroupBubble()); + this, u"mousemove"_ns, TrustedEventsAtSystemGroupBubble()); if (aForGrabber) { mListeningToMouseMoveEventForGrabber = true; } else { @@ -168,7 +167,7 @@ nsresult HTMLEditorEventListener::ListenToMouseMoveEventForResizersOrGrabber( } eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("mousemove"), TrustedEventsAtSystemGroupBubble()); + this, u"mousemove"_ns, TrustedEventsAtSystemGroupBubble()); if (aForGrabber) { mListeningToMouseMoveEventForGrabber = false; } else { @@ -216,13 +215,13 @@ nsresult HTMLEditorEventListener::ListenToWindowResizeEvent(bool aListen) { if (aListen) { eventListenerManager->AddEventListenerByType( - this, NS_LITERAL_STRING("resize"), TrustedEventsAtSystemGroupBubble()); + this, u"resize"_ns, TrustedEventsAtSystemGroupBubble()); mListeningToResizeEvent = true; return NS_OK; } eventListenerManager->RemoveEventListenerByType( - this, NS_LITERAL_STRING("resize"), TrustedEventsAtSystemGroupBubble()); + this, u"resize"_ns, TrustedEventsAtSystemGroupBubble()); mListeningToResizeEvent = false; return NS_OK; } diff --git a/editor/libeditor/HTMLEditorObjectResizer.cpp b/editor/libeditor/HTMLEditorObjectResizer.cpp index d404d698c0e0..2514047a8bc6 100644 --- a/editor/libeditor/HTMLEditorObjectResizer.cpp +++ b/editor/libeditor/HTMLEditorObjectResizer.cpp @@ -35,14 +35,14 @@ #include "nscore.h" #include -#define kTopLeft NS_LITERAL_STRING("nw") -#define kTop NS_LITERAL_STRING("n") -#define kTopRight NS_LITERAL_STRING("ne") -#define kLeft NS_LITERAL_STRING("w") -#define kRight NS_LITERAL_STRING("e") -#define kBottomLeft NS_LITERAL_STRING("sw") -#define kBottom NS_LITERAL_STRING("s") -#define kBottomRight NS_LITERAL_STRING("se") +#define kTopLeft u"nw"_ns +#define kTop u"n"_ns +#define kTopRight u"ne"_ns +#define kLeft u"w"_ns +#define kRight u"e"_ns +#define kBottomLeft u"sw"_ns +#define kBottom u"s"_ns +#define kBottomRight u"se"_ns namespace mozilla { @@ -54,8 +54,8 @@ using namespace dom; ManualNACPtr HTMLEditor::CreateResizer(int16_t aLocation, nsIContent& aParentContent) { - ManualNACPtr resizer = CreateAnonymousElement( - nsGkAtoms::span, aParentContent, NS_LITERAL_STRING("mozResizer"), false); + ManualNACPtr resizer = CreateAnonymousElement(nsGkAtoms::span, aParentContent, + u"mozResizer"_ns, false); if (!resizer) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::span, mozResizer) " @@ -64,8 +64,8 @@ ManualNACPtr HTMLEditor::CreateResizer(int16_t aLocation, } // add the mouse listener so we can detect a click on a resizer - DebugOnly rvIgnored = resizer->AddEventListener( - NS_LITERAL_STRING("mousedown"), mEventListener, true); + DebugOnly rvIgnored = + resizer->AddEventListener(u"mousedown"_ns, mEventListener, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "EventTarget::AddEventListener(mousedown) failed, but ignored"); @@ -118,14 +118,14 @@ ManualNACPtr HTMLEditor::CreateShadow(nsIContent& aParentContent, name = nsGkAtoms::span; } - return CreateAnonymousElement(name, aParentContent, - NS_LITERAL_STRING("mozResizingShadow"), true); + return CreateAnonymousElement(name, aParentContent, u"mozResizingShadow"_ns, + true); } ManualNACPtr HTMLEditor::CreateResizingInfo(nsIContent& aParentContent) { // let's create an info box through the element factory return CreateAnonymousElement(nsGkAtoms::span, aParentContent, - NS_LITERAL_STRING("mozResizingInfo"), true); + u"mozResizingInfo"_ns, true); } nsresult HTMLEditor::SetAllResizersPosition() { @@ -505,9 +505,8 @@ nsresult HTMLEditor::ShowResizersInternal(Element& aResizedElement) { // XXX Even when it failed to add event listener, should we need to set // _moz_resizing attribute? - DebugOnly rvIgnored = - aResizedElement.SetAttr(kNameSpaceID_None, nsGkAtoms::_moz_resizing, - NS_LITERAL_STRING("true"), true); + DebugOnly rvIgnored = aResizedElement.SetAttr( + kNameSpaceID_None, nsGkAtoms::_moz_resizing, u"true"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::_moz_resizing, true) failed, but ignored"); @@ -641,17 +640,15 @@ nsresult HTMLEditor::HideResizersInternal() { void HTMLEditor::HideShadowAndInfo() { if (mResizingShadow) { - DebugOnly rvIgnored = - mResizingShadow->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("hidden"), true); + DebugOnly rvIgnored = mResizingShadow->SetAttr( + kNameSpaceID_None, nsGkAtoms::_class, u"hidden"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::_class, hidden) failed, but ignored"); } if (mResizingInfo) { - DebugOnly rvIgnored = - mResizingInfo->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("hidden"), true); + DebugOnly rvIgnored = mResizingInfo->SetAttr( + kNameSpaceID_None, nsGkAtoms::_class, u"hidden"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::_class, hidden) failed, but ignored"); @@ -664,9 +661,8 @@ nsresult HTMLEditor::StartResizing(Element* aHandle) { return NS_ERROR_FAILURE; } mActivatedHandle = aHandle; - DebugOnly rvIgnored = - mActivatedHandle->SetAttr(kNameSpaceID_None, nsGkAtoms::_moz_activated, - NS_LITERAL_STRING("true"), true); + DebugOnly rvIgnored = mActivatedHandle->SetAttr( + kNameSpaceID_None, nsGkAtoms::_moz_activated, u"true"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::_moz_activated, true) failed"); @@ -808,9 +804,8 @@ nsresult HTMLEditor::OnMouseUp(int32_t aClientX, int32_t aClientY) { } if (mIsMoving) { - DebugOnly rvIgnored = - mPositioningShadow->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("hidden"), true); + DebugOnly rvIgnored = mPositioningShadow->SetAttr( + kNameSpaceID_None, nsGkAtoms::_class, u"hidden"_ns, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::_class, hidden) failed"); @@ -912,10 +907,8 @@ nsresult HTMLEditor::SetResizingInfoPosition(int32_t aX, int32_t aY, int32_t aW, diffWidthStr.AppendInt(diffWidth); diffHeightStr.AppendInt(diffHeight); - nsAutoString info(widthStr + NS_LITERAL_STRING(" x ") + heightStr + - NS_LITERAL_STRING(" (") + diffWidthStr + - NS_LITERAL_STRING(", ") + diffHeightStr + - NS_LITERAL_STRING(")")); + nsAutoString info(widthStr + u" x "_ns + heightStr + u" ("_ns + diffWidthStr + + u", "_ns + diffHeightStr + u")"_ns); RefPtr document = GetDocument(); textInfo = document->CreateTextNode(info); diff --git a/editor/libeditor/HTMLInlineTableEditor.cpp b/editor/libeditor/HTMLInlineTableEditor.cpp index c9e66458873b..5fcc55845c20 100644 --- a/editor/libeditor/HTMLInlineTableEditor.cpp +++ b/editor/libeditor/HTMLInlineTableEditor.cpp @@ -65,8 +65,7 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { // If buttons are just created again for same element, we hit the former // check. ManualNACPtr addColumnBeforeButton = CreateAnonymousElement( - nsGkAtoms::a, *rootElement, - NS_LITERAL_STRING("mozTableAddColumnBefore"), false); + nsGkAtoms::a, *rootElement, u"mozTableAddColumnBefore"_ns, false); if (NS_WARN_IF(!addColumnBeforeButton)) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -80,8 +79,7 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { mAddColumnBeforeButton = std::move(addColumnBeforeButton); ManualNACPtr removeColumnButton = CreateAnonymousElement( - nsGkAtoms::a, *rootElement, NS_LITERAL_STRING("mozTableRemoveColumn"), - false); + nsGkAtoms::a, *rootElement, u"mozTableRemoveColumn"_ns, false); if (!removeColumnButton) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -95,8 +93,7 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { mRemoveColumnButton = std::move(removeColumnButton); ManualNACPtr addColumnAfterButton = CreateAnonymousElement( - nsGkAtoms::a, *rootElement, NS_LITERAL_STRING("mozTableAddColumnAfter"), - false); + nsGkAtoms::a, *rootElement, u"mozTableAddColumnAfter"_ns, false); if (!addColumnAfterButton) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -110,8 +107,7 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { mAddColumnAfterButton = std::move(addColumnAfterButton); ManualNACPtr addRowBeforeButton = CreateAnonymousElement( - nsGkAtoms::a, *rootElement, NS_LITERAL_STRING("mozTableAddRowBefore"), - false); + nsGkAtoms::a, *rootElement, u"mozTableAddRowBefore"_ns, false); if (!addRowBeforeButton) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -124,9 +120,8 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { } mAddRowBeforeButton = std::move(addRowBeforeButton); - ManualNACPtr removeRowButton = - CreateAnonymousElement(nsGkAtoms::a, *rootElement, - NS_LITERAL_STRING("mozTableRemoveRow"), false); + ManualNACPtr removeRowButton = CreateAnonymousElement( + nsGkAtoms::a, *rootElement, u"mozTableRemoveRow"_ns, false); if (!removeRowButton) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -139,9 +134,8 @@ nsresult HTMLEditor::ShowInlineTableEditingUIInternal(Element& aCellElement) { } mRemoveRowButton = std::move(removeRowButton); - ManualNACPtr addRowAfterButton = - CreateAnonymousElement(nsGkAtoms::a, *rootElement, - NS_LITERAL_STRING("mozTableAddRowAfter"), false); + ManualNACPtr addRowAfterButton = CreateAnonymousElement( + nsGkAtoms::a, *rootElement, u"mozTableAddRowAfter"_ns, false); if (!addRowAfterButton) { NS_WARNING( "HTMLEditor::CreateAnonymousElement(nsGkAtoms::a, " @@ -211,7 +205,7 @@ nsresult HTMLEditor::DoInlineTableEditingAction(const Element& aElement) { nsAutoString anonclass; aElement.GetAttr(kNameSpaceID_None, nsGkAtoms::_moz_anonclass, anonclass); - if (!StringBeginsWith(anonclass, NS_LITERAL_STRING("mozTable"))) { + if (!StringBeginsWith(anonclass, u"mozTable"_ns)) { return NS_OK; } @@ -362,8 +356,8 @@ void HTMLEditor::AddMouseClickListener(Element* aElement) { if (NS_WARN_IF(!aElement)) { return; } - DebugOnly rvIgnored = aElement->AddEventListener( - NS_LITERAL_STRING("click"), mEventListener, true); + DebugOnly rvIgnored = + aElement->AddEventListener(u"click"_ns, mEventListener, true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "EventTarget::AddEventListener(click) failed, but ignored"); @@ -373,8 +367,7 @@ void HTMLEditor::RemoveMouseClickListener(Element* aElement) { if (NS_WARN_IF(!aElement)) { return; } - aElement->RemoveEventListener(NS_LITERAL_STRING("click"), mEventListener, - true); + aElement->RemoveEventListener(u"click"_ns, mEventListener, true); } NS_IMETHODIMP HTMLEditor::RefreshInlineTableEditingUI() { diff --git a/editor/libeditor/HTMLStyleEditor.cpp b/editor/libeditor/HTMLStyleEditor.cpp index f86411be45d5..7ad0140e5bc3 100644 --- a/editor/libeditor/HTMLStyleEditor.cpp +++ b/editor/libeditor/HTMLStyleEditor.cpp @@ -1188,7 +1188,7 @@ bool HTMLEditor::IsOnlyAttribute(const Element* aElement, nsAtom* aAttribute) { if (name->LocalName() != aAttribute) { nsAutoString attrString; name->LocalName()->ToString(attrString); - if (!StringBeginsWith(attrString, NS_LITERAL_STRING("_moz"))) { + if (!StringBeginsWith(attrString, u"_moz"_ns)) { return false; } } @@ -1954,7 +1954,7 @@ nsresult HTMLEditor::RemoveInlinePropertyInternal( DebugOnly rvIgnored = SetInlinePropertyOnNode( MOZ_KnownLive(content), MOZ_KnownLive(*style.mProperty), MOZ_KnownLive(style.mAttribute), - NS_LITERAL_STRING("-moz-editor-invert-value")); + u"-moz-editor-invert-value"_ns); if (NS_WARN_IF(Destroyed())) { return NS_ERROR_EDITOR_DESTROYED; } @@ -1979,7 +1979,7 @@ nsresult HTMLEditor::RemoveInlinePropertyInternal( nsresult rv = SetInlinePropertyOnTextNode( MOZ_KnownLive(*content->AsText()), startOffset, endOffset, MOZ_KnownLive(*style.mProperty), MOZ_KnownLive(style.mAttribute), - NS_LITERAL_STRING("-moz-editor-invert-value")); + u"-moz-editor-invert-value"_ns); if (NS_FAILED(rv)) { NS_WARNING( "HTMLEditor::SetInlinePropertyOnTextNode(-moz-editor-invert-" @@ -2017,7 +2017,7 @@ nsresult HTMLEditor::RemoveInlinePropertyInternal( MOZ_KnownLive(textNode), 0, textNode->TextLength(), MOZ_KnownLive(*style.mProperty), MOZ_KnownLive(style.mAttribute), - NS_LITERAL_STRING("-moz-editor-invert-value")); + u"-moz-editor-invert-value"_ns); if (NS_FAILED(rv)) { NS_WARNING( "HTMLEditor::SetInlinePropertyOnTextNode(-moz-editor-invert-" diff --git a/editor/libeditor/TextEditSubActionHandler.cpp b/editor/libeditor/TextEditSubActionHandler.cpp index 6b3ce4d690e4..619269bce2d2 100644 --- a/editor/libeditor/TextEditSubActionHandler.cpp +++ b/editor/libeditor/TextEditSubActionHandler.cpp @@ -194,7 +194,7 @@ EditActionResult TextEditor::InsertLineFeedCharacterAtSelection() { CANCEL_OPERATION_AND_RETURN_EDIT_ACTION_RESULT_IF_READONLY if (mMaxTextLength >= 0) { - nsAutoString insertionString(NS_LITERAL_STRING("\n")); + nsAutoString insertionString(u"\n"_ns); EditActionResult result = MaybeTruncateInsertionStringForMaxLength(insertionString); if (result.Failed()) { @@ -248,8 +248,8 @@ EditActionResult TextEditor::InsertLineFeedCharacterAtSelection() { // Insert a linefeed character. EditorRawDOMPoint pointAfterInsertedLineFeed; - rv = InsertTextWithTransaction(*document, NS_LITERAL_STRING("\n"), - pointToInsert, &pointAfterInsertedLineFeed); + rv = InsertTextWithTransaction(*document, u"\n"_ns, pointToInsert, + &pointAfterInsertedLineFeed); if (!pointAfterInsertedLineFeed.IsSet()) { NS_WARNING( "EditorBase::InsertTextWithTransaction(\\n) didn't return position of " diff --git a/editor/libeditor/TextEditor.cpp b/editor/libeditor/TextEditor.cpp index 12096b3d4621..1b10cfd24efb 100644 --- a/editor/libeditor/TextEditor.cpp +++ b/editor/libeditor/TextEditor.cpp @@ -182,7 +182,7 @@ NS_IMETHODIMP TextEditor::SetDocumentCharacterSet( } RefPtr headElementList = - document->GetElementsByTagName(NS_LITERAL_STRING("head")); + document->GetElementsByTagName(u"head"_ns); if (NS_WARN_IF(!headElementList)) { return NS_OK; } @@ -210,14 +210,13 @@ NS_IMETHODIMP TextEditor::SetDocumentCharacterSet( // not undoable, undo should undo CreateNodeWithTransaction(). DebugOnly rvIgnored = NS_OK; rvIgnored = metaElement->SetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, - NS_LITERAL_STRING("Content-Type"), true); + u"Content-Type"_ns, true); NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::httpEquiv, Content-Type) " "failed, but ignored"); - rvIgnored = metaElement->SetAttr(kNameSpaceID_None, nsGkAtoms::content, - NS_LITERAL_STRING("text/html;charset=") + - NS_ConvertASCIItoUTF16(characterSet), - true); + rvIgnored = metaElement->SetAttr( + kNameSpaceID_None, nsGkAtoms::content, + u"text/html;charset="_ns + NS_ConvertASCIItoUTF16(characterSet), true); NS_WARNING_ASSERTION( NS_SUCCEEDED(rvIgnored), "Element::SetAttr(nsGkAtoms::content) failed, but ignored"); @@ -228,7 +227,7 @@ bool TextEditor::UpdateMetaCharset(Document& aDocument, const nsACString& aCharacterSet) { // get a list of META tags RefPtr metaElementList = - aDocument.GetElementsByTagName(NS_LITERAL_STRING("meta")); + aDocument.GetElementsByTagName(u"meta"_ns); if (NS_WARN_IF(!metaElementList)) { return false; } @@ -240,7 +239,7 @@ bool TextEditor::UpdateMetaCharset(Document& aDocument, nsAutoString currentValue; metaElement->GetAttr(kNameSpaceID_None, nsGkAtoms::httpEquiv, currentValue); - if (!FindInReadable(NS_LITERAL_STRING("content-type"), currentValue, + if (!FindInReadable(u"content-type"_ns, currentValue, nsCaseInsensitiveStringComparator)) { continue; } @@ -339,7 +338,7 @@ nsresult TextEditor::HandleKeyPressEvent(WidgetKeyboardEvent* aKeyboardEvent) { // else we insert the tab straight through aKeyboardEvent->PreventDefault(); - nsresult rv = OnInputText(NS_LITERAL_STRING("\t")); + nsresult rv = OnInputText(u"\t"_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "TextEditor::OnInputText(\\t) failed"); return rv; @@ -1084,7 +1083,7 @@ nsresult TextEditor::RedoAsAction(uint32_t aCount, nsIPrincipal* aPrincipal) { // XXX Looks like that this is too slow if there are a lot of nodes. // Shouldn't we just scan children in the root? nsCOMPtr nodeList = - mRootElement->GetElementsByTagName(NS_LITERAL_STRING("br")); + mRootElement->GetElementsByTagName(u"br"_ns); MOZ_ASSERT(nodeList); Element* brElement = nodeList->Length() == 1 ? nodeList->Item(0) : nullptr; @@ -1517,8 +1516,7 @@ nsresult TextEditor::SharedOutputString(uint32_t aFlags, bool* aIsCollapsed, aFlags |= nsIDocumentEncoder::OutputSelectionOnly; } // If the selection isn't collapsed, we'll use the whole document. - nsresult rv = - ComputeValueInternal(NS_LITERAL_STRING("text/plain"), aFlags, aResult); + nsresult rv = ComputeValueInternal(u"text/plain"_ns, aFlags, aResult); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "TextEditor::ComputeValueInternal(text/plain) failed"); return rv; @@ -1821,8 +1819,8 @@ MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODIMP TextEditor::Notify(nsITimer* aTimer) { if (RefPtr target = GetInputEventTargetElement()) { RefPtr document = target->OwnerDoc(); DebugOnly rvIgnored = nsContentUtils::DispatchTrustedEvent( - document, target, NS_LITERAL_STRING("MozLastInputMasked"), - CanBubble::eYes, Cancelable::eNo); + document, target, u"MozLastInputMasked"_ns, CanBubble::eYes, + Cancelable::eNo); NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored), "nsContentUtils::DispatchTrustedEvent(" "MozLastInputMasked) failed, but ignored"); diff --git a/editor/libeditor/TextEditor.h b/editor/libeditor/TextEditor.h index 5525dc222536..a254522691b2 100644 --- a/editor/libeditor/TextEditor.h +++ b/editor/libeditor/TextEditor.h @@ -292,8 +292,8 @@ class TextEditor : public EditorBase, public nsITimerCallback, public nsINamed { if (NS_WARN_IF(!editActionData.CanHandle())) { return NS_ERROR_NOT_INITIALIZED; } - nsresult rv = ComputeValueInternal(NS_LITERAL_STRING("text/plain"), - aDocumentEncoderFlags, aOutputString); + nsresult rv = ComputeValueInternal(u"text/plain"_ns, aDocumentEncoderFlags, + aOutputString); if (NS_WARN_IF(NS_FAILED(rv))) { return EditorBase::ToGenericNSResult(rv); } diff --git a/editor/libeditor/TextEditorDataTransfer.cpp b/editor/libeditor/TextEditorDataTransfer.cpp index 8b1d2f746601..215ce323ad11 100644 --- a/editor/libeditor/TextEditorDataTransfer.cpp +++ b/editor/libeditor/TextEditorDataTransfer.cpp @@ -443,7 +443,7 @@ nsresult TextEditor::OnDrop(DragEvent* aDropEvent) { uint32_t textLength = 0; for (uint32_t i = 0; i < numItems; ++i) { nsCOMPtr data; - dataTransfer->GetDataAtNoSecurityCheck(NS_LITERAL_STRING("text/plain"), i, + dataTransfer->GetDataAtNoSecurityCheck(u"text/plain"_ns, i, getter_AddRefs(data)); if (!data) { continue; diff --git a/editor/libeditor/WSRunObject.cpp b/editor/libeditor/WSRunObject.cpp index 29082ab00d3f..9acd80297bc2 100644 --- a/editor/libeditor/WSRunObject.cpp +++ b/editor/libeditor/WSRunObject.cpp @@ -1777,8 +1777,7 @@ nsresult WSRunObject::NormalizeWhiteSpacesAtEndOf(const WSFragment& aRun) { MOZ_KnownLive(mHTMLEditor) .ReplaceTextWithTransaction( MOZ_KnownLive(*atPreviousCharOfEndOfRun.ContainerAsText()), - atPreviousCharOfEndOfRun.Offset(), 1, - NS_LITERAL_STRING(" ")); + atPreviousCharOfEndOfRun.Offset(), 1, u" "_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::ReplaceTextWithTransaction() failed"); return rv; @@ -1823,7 +1822,7 @@ nsresult WSRunObject::NormalizeWhiteSpacesAtEndOf(const WSFragment& aRun) { .ReplaceTextWithTransaction( MOZ_KnownLive(*atFirstASCIIWhiteSpace.ContainerAsText()), atFirstASCIIWhiteSpace.Offset(), replaceLengthInStartNode, - NS_LITERAL_STRING(u"\x00A0 ")); + u"\x00A0 "_ns); if (NS_FAILED(rv)) { NS_WARNING("HTMLEditor::ReplaceTextWithTransaction() failed"); return rv; @@ -1934,7 +1933,7 @@ nsresult WSRunObject::MaybeReplacePreviousNBSPWithASCIIWhiteSpace( nsresult rv = MOZ_KnownLive(mHTMLEditor) .ReplaceTextWithTransaction( MOZ_KnownLive(*atPreviousChar.ContainerAsText()), - atPreviousChar.Offset(), 1, NS_LITERAL_STRING(" ")); + atPreviousChar.Offset(), 1, u" "_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::ReplaceTextWithTransaction() failed"); return rv; @@ -1975,7 +1974,7 @@ nsresult WSRunObject::MaybeReplaceInclusiveNextNBSPWithASCIIWhiteSpace( nsresult rv = MOZ_KnownLive(mHTMLEditor) .ReplaceTextWithTransaction( MOZ_KnownLive(*atNextChar.ContainerAsText()), - atNextChar.Offset(), 1, NS_LITERAL_STRING(" ")); + atNextChar.Offset(), 1, u" "_ns); NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "HTMLEditor::ReplaceTextWithTransaction() failed"); return rv; diff --git a/editor/spellchecker/EditorSpellCheck.cpp b/editor/spellchecker/EditorSpellCheck.cpp index 36779b8da4bf..131c0028c12a 100644 --- a/editor/spellchecker/EditorSpellCheck.cpp +++ b/editor/spellchecker/EditorSpellCheck.cpp @@ -65,7 +65,7 @@ class UpdateDictionaryHolder { } }; -#define CPS_PREF_NAME NS_LITERAL_STRING("spellcheck.lang") +#define CPS_PREF_NAME u"spellcheck.lang"_ns /** * Gets the URI of aEditor's document. diff --git a/editor/spellchecker/nsComposeTxtSrvFilter.cpp b/editor/spellchecker/nsComposeTxtSrvFilter.cpp index f01aaddb97af..7ab6eae8cb11 100644 --- a/editor/spellchecker/nsComposeTxtSrvFilter.cpp +++ b/editor/spellchecker/nsComposeTxtSrvFilter.cpp @@ -47,9 +47,9 @@ bool nsComposeTxtSrvFilter::Skip(nsINode* aNode) const { } if (aNode->IsHTMLElement(nsGkAtoms::table)) { - return aNode->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("moz-email-headers-table"), eCaseMatters); + return aNode->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::_class, + u"moz-email-headers-table"_ns, + eCaseMatters); } return false; diff --git a/extensions/auth/nsAuthSSPI.cpp b/extensions/auth/nsAuthSSPI.cpp index 2d038f59f759..27c42fed0439 100644 --- a/extensions/auth/nsAuthSSPI.cpp +++ b/extensions/auth/nsAuthSSPI.cpp @@ -124,7 +124,7 @@ nsresult nsAuthSSPI::MakeSN(const char* principal, nsCString& result) { nsAutoCString cname; rv = record->GetCanonicalName(cname); if (NS_SUCCEEDED(rv)) { - result = StringHead(buf, index) + NS_LITERAL_CSTRING("/") + cname; + result = StringHead(buf, index) + "/"_ns + cname; LOG(("Using SPN of [%s]\n", result.get())); } return rv; diff --git a/extensions/auth/nsAuthSambaNTLM.cpp b/extensions/auth/nsAuthSambaNTLM.cpp index 1d6a3c3ebaf8..37f53d1e7918 100644 --- a/extensions/auth/nsAuthSambaNTLM.cpp +++ b/extensions/auth/nsAuthSambaNTLM.cpp @@ -173,11 +173,10 @@ nsresult nsAuthSambaNTLM::SpawnNTLMAuthHelper() { &mFromChildFD, &mToChildFD); if (!isOK) return NS_ERROR_FAILURE; - if (!WriteString(mToChildFD, NS_LITERAL_CSTRING("YR\n"))) - return NS_ERROR_FAILURE; + if (!WriteString(mToChildFD, "YR\n"_ns)) return NS_ERROR_FAILURE; nsCString line; if (!ReadLine(mFromChildFD, line)) return NS_ERROR_FAILURE; - if (!StringBeginsWith(line, NS_LITERAL_CSTRING("YR "))) { + if (!StringBeginsWith(line, "YR "_ns)) { // Something went wrong. Perhaps no credentials are accessible. return NS_ERROR_FAILURE; } @@ -231,8 +230,7 @@ nsAuthSambaNTLM::GetNextToken(const void* inToken, uint32_t inTokenLen, if (!WriteString(mToChildFD, request)) return NS_ERROR_FAILURE; nsCString line; if (!ReadLine(mFromChildFD, line)) return NS_ERROR_FAILURE; - if (!StringBeginsWith(line, NS_LITERAL_CSTRING("KK ")) && - !StringBeginsWith(line, NS_LITERAL_CSTRING("AF "))) { + if (!StringBeginsWith(line, "KK "_ns) && !StringBeginsWith(line, "AF "_ns)) { // Something went wrong. Perhaps no credentials are accessible. return NS_ERROR_FAILURE; } diff --git a/extensions/permissions/PermissionManager.cpp b/extensions/permissions/PermissionManager.cpp index 3cf610a77e86..5c95437f714e 100644 --- a/extensions/permissions/PermissionManager.cpp +++ b/extensions/permissions/PermissionManager.cpp @@ -96,9 +96,8 @@ bool HasDefaultPref(const nsACString& aType) { // A list of permissions that can have a fallback default permission // set under the permissions.default.* pref. static const nsLiteralCString kPermissionsWithDefaults[] = { - NS_LITERAL_CSTRING("camera"), NS_LITERAL_CSTRING("microphone"), - NS_LITERAL_CSTRING("geo"), NS_LITERAL_CSTRING("desktop-notification"), - NS_LITERAL_CSTRING("shortcuts")}; + "camera"_ns, "microphone"_ns, "geo"_ns, "desktop-notification"_ns, + "shortcuts"_ns}; if (!aType.IsEmpty()) { for (const auto& perm : kPermissionsWithDefaults) { @@ -122,19 +121,16 @@ static const nsLiteralCString kPreloadPermissions[] = { // interception when a user has disabled storage for a specific site. Once // service worker interception moves to the parent process this should be // removed. See bug 1428130. - NS_LITERAL_CSTRING("cookie")}; + "cookie"_ns}; // Certain permissions should never be persisted to disk under GeckoView; it's // the responsibility of the app to manage storing these beyond the scope of // a single session. #ifdef ANDROID static const nsLiteralCString kGeckoViewRestrictedPermissions[] = { - NS_LITERAL_CSTRING("MediaManagerVideo"), - NS_LITERAL_CSTRING("geolocation"), - NS_LITERAL_CSTRING("desktop-notification"), - NS_LITERAL_CSTRING("persistent-storage"), - NS_LITERAL_CSTRING("trackingprotection"), - NS_LITERAL_CSTRING("trackingprotection-pb")}; + "MediaManagerVideo"_ns, "geolocation"_ns, + "desktop-notification"_ns, "persistent-storage"_ns, + "trackingprotection"_ns, "trackingprotection-pb"_ns}; #endif // NOTE: nullptr can be passed as aType - if it is this function will return @@ -160,7 +156,7 @@ bool IsPreloadPermission(const nsACString& aType) { // Non-preloaded, but OA stripped permissions would not be accessible by sites // in private browsing / non-default user context. static constexpr std::array kStripOAPermissions = { - {NS_LITERAL_CSTRING("cookie")}}; + {"cookie"_ns}}; bool IsOAForceStripPermission(const nsACString& aType) { if (aType.IsEmpty()) { @@ -511,8 +507,7 @@ nsresult UpgradeHostToOriginAndInsert( } // http:// URI default - rv = NS_NewURI(getter_AddRefs(uri), - NS_LITERAL_CSTRING("http://") + hostSegment); + rv = NS_NewURI(getter_AddRefs(uri), "http://"_ns + hostSegment); NS_ENSURE_SUCCESS(rv, rv); rv = GetPrincipal(uri, aIsInIsolatedMozBrowserElement, @@ -527,8 +522,7 @@ nsresult UpgradeHostToOriginAndInsert( aModificationTime); // https:// URI default - rv = NS_NewURI(getter_AddRefs(uri), - NS_LITERAL_CSTRING("https://") + hostSegment); + rv = NS_NewURI(getter_AddRefs(uri), "https://"_ns + hostSegment); NS_ENSURE_SUCCESS(rv, rv); rv = GetPrincipal(uri, aIsInIsolatedMozBrowserElement, @@ -771,8 +765,8 @@ void PermissionManager::InitDB(bool aRemoveFile) { } } - rv = mPermissionsFile->AppendNative( - NS_LITERAL_CSTRING(PERMISSIONS_FILE_NAME)); + rv = + mPermissionsFile->AppendNative(nsLiteralCString(PERMISSIONS_FILE_NAME)); NS_ENSURE_SUCCESS_VOID(rv); } @@ -835,8 +829,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, rv = OpenDatabase(mPermissionsFile); if (rv == NS_ERROR_FILE_CORRUPTED) { - LogToConsole( - NS_LITERAL_STRING("permissions.sqlite is corrupted! Try again!")); + LogToConsole(u"permissions.sqlite is corrupted! Try again!"_ns); // Add telemetry probe Telemetry::Accumulate(Telemetry::PERMISSIONS_SQL_CORRUPTED, 1); @@ -844,13 +837,11 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // delete corrupted permissions.sqlite and try again rv = mPermissionsFile->Remove(false); NS_ENSURE_SUCCESS(rv, rv); - LogToConsole( - NS_LITERAL_STRING("Corrupted permissions.sqlite has been removed.")); + LogToConsole(u"Corrupted permissions.sqlite has been removed."_ns); rv = OpenDatabase(mPermissionsFile); NS_ENSURE_SUCCESS(rv, rv); - LogToConsole( - NS_LITERAL_STRING("OpenDatabase to permissions.sqlite is successful!")); + LogToConsole(u"OpenDatabase to permissions.sqlite is successful!"_ns); } if (NS_WARN_IF(NS_FAILED(rv))) { @@ -860,31 +851,29 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, bool ready; data->mDBConn->GetConnectionReady(&ready); if (!ready) { - LogToConsole(NS_LITERAL_STRING( - "Fail to get connection to permissions.sqlite! Try again!")); + LogToConsole(nsLiteralString( + u"Fail to get connection to permissions.sqlite! Try again!")); // delete and try again rv = mPermissionsFile->Remove(false); NS_ENSURE_SUCCESS(rv, rv); - LogToConsole( - NS_LITERAL_STRING("Defective permissions.sqlite has been removed.")); + LogToConsole(u"Defective permissions.sqlite has been removed."_ns); // Add telemetry probe Telemetry::Accumulate(Telemetry::DEFECTIVE_PERMISSIONS_SQL_REMOVED, 1); rv = OpenDatabase(mPermissionsFile); NS_ENSURE_SUCCESS(rv, rv); - LogToConsole( - NS_LITERAL_STRING("OpenDatabase to permissions.sqlite is successful!")); + LogToConsole(u"OpenDatabase to permissions.sqlite is successful!"_ns); data->mDBConn->GetConnectionReady(&ready); if (!ready) return NS_ERROR_UNEXPECTED; } bool tableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_perms"), &tableExists); + data->mDBConn->TableExists("moz_perms"_ns, &tableExists); if (!tableExists) { - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts"), &tableExists); + data->mDBConn->TableExists("moz_hosts"_ns, &tableExists); } if (!tableExists) { rv = CreateTable(); @@ -905,11 +894,11 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // previous non-expiry version of database. Upgrade it by adding // the expiration columns rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_hosts ADD expireType INTEGER")); + "ALTER TABLE moz_hosts ADD expireType INTEGER"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_hosts ADD expireTime INTEGER")); + "ALTER TABLE moz_hosts ADD expireTime INTEGER"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -922,10 +911,10 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, case 2: { // Add appId/isInBrowserElement fields. rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_hosts ADD appId INTEGER")); + "ALTER TABLE moz_hosts ADD appId INTEGER"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_hosts ADD isInBrowserElement INTEGER")); NS_ENSURE_SUCCESS(rv, rv); @@ -938,7 +927,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // Version 3->4 is the creation of the modificationTime field. case 3: { - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_hosts ADD modificationTime INTEGER")); NS_ENSURE_SUCCESS(rv, rv); @@ -997,12 +986,11 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // visible in previous versions of firefox. bool permsTableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_perms"), - &permsTableExists); + data->mDBConn->TableExists("moz_perms"_ns, &permsTableExists); if (!permsTableExists) { // Move the upgraded database to moz_perms - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "ALTER TABLE moz_hosts RENAME TO moz_perms")); + rv = data->mDBConn->ExecuteSimpleSQL( + "ALTER TABLE moz_hosts RENAME TO moz_perms"_ns); NS_ENSURE_SUCCESS(rv, rv); } else { NS_WARNING( @@ -1020,26 +1008,23 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // user actually wants to use. We have to get rid of moz_hosts // such that moz_hosts_v4 can be moved into its place if it // exists. - rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_hosts")); + rv = data->mDBConn->ExecuteSimpleSQL("DROP TABLE moz_hosts"_ns); NS_ENSURE_SUCCESS(rv, rv); } #ifdef DEBUG // The moz_hosts table shouldn't exist anymore bool hostsTableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts"), - &hostsTableExists); + data->mDBConn->TableExists("moz_hosts"_ns, &hostsTableExists); MOZ_ASSERT(!hostsTableExists); #endif // Rename moz_hosts_v4 back to it's original location, if it // exists bool v4TableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts_v4"), - &v4TableExists); + data->mDBConn->TableExists("moz_hosts_v4"_ns, &v4TableExists); if (v4TableExists) { - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_hosts_v4 RENAME TO moz_hosts")); NS_ENSURE_SUCCESS(rv, rv); } @@ -1064,8 +1049,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, case 4: case 6: { bool hostsTableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts"), - &hostsTableExists); + data->mDBConn->TableExists("moz_hosts"_ns, &hostsTableExists); if (hostsTableExists) { // Both versions 4 and 6 have a version 4 formatted hosts table // named moz_hosts. We can migrate this table to our version 7 @@ -1076,32 +1060,30 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, NS_ENSURE_SUCCESS(rv, rv); bool tableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts_new"), - &tableExists); + data->mDBConn->TableExists("moz_hosts_new"_ns, &tableExists); if (tableExists) { NS_WARNING( "The temporary database moz_hosts_new already exists, " "dropping " "it."); - rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_hosts_new")); + rv = data->mDBConn->ExecuteSimpleSQL("DROP TABLE moz_hosts_new"_ns); NS_ENSURE_SUCCESS(rv, rv); } rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_hosts_new (" - " id INTEGER PRIMARY KEY" - ",origin TEXT" - ",type TEXT" - ",permission INTEGER" - ",expireType INTEGER" - ",expireTime INTEGER" - ",modificationTime INTEGER" - ")")); + nsLiteralCString("CREATE TABLE moz_hosts_new (" + " id INTEGER PRIMARY KEY" + ",origin TEXT" + ",type TEXT" + ",permission INTEGER" + ",expireType INTEGER" + ",expireTime INTEGER" + ",modificationTime INTEGER" + ")")); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr stmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT host, type, permission, expireType, " "expireTime, " "modificationTime, isInBrowserElement FROM moz_hosts"), @@ -1141,13 +1123,12 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // intended to act as a backup. If this table is not present, // then the moz_hosts table was created as a random empty table. rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_hosts_is_backup (dummy " - "INTEGER PRIMARY KEY)")); + nsLiteralCString("CREATE TABLE moz_hosts_is_backup (dummy " + "INTEGER PRIMARY KEY)")); NS_ENSURE_SUCCESS(rv, rv); bool permsTableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_perms"), - &permsTableExists); + data->mDBConn->TableExists("moz_perms"_ns, &permsTableExists); if (permsTableExists) { // The user already had a moz_perms table, and we are // performing a re-migration. We count the rows in the old @@ -1156,8 +1137,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, nsCOMPtr countStmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT COUNT(*) FROM moz_perms"), - getter_AddRefs(countStmt)); + "SELECT COUNT(*) FROM moz_perms"_ns, getter_AddRefs(countStmt)); bool hasResult = false; if (NS_FAILED(rv) || NS_FAILED(countStmt->ExecuteStep(&hasResult)) || !hasResult) { @@ -1166,12 +1146,12 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // Back up the old moz_perms database as moz_perms_v6 before // we move the new table into its position - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_perms RENAME TO moz_perms_v6")); NS_ENSURE_SUCCESS(rv, rv); } - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_hosts_new RENAME TO moz_perms")); NS_ENSURE_SUCCESS(rv, rv); @@ -1181,17 +1161,17 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // We don't have a moz_hosts table, so we create one for // downgrading purposes. This table is empty. rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_hosts (" - " id INTEGER PRIMARY KEY" - ",host TEXT" - ",type TEXT" - ",permission INTEGER" - ",expireType INTEGER" - ",expireTime INTEGER" - ",modificationTime INTEGER" - ",appId INTEGER" - ",isInBrowserElement INTEGER" - ")")); + nsLiteralCString("CREATE TABLE moz_hosts (" + " id INTEGER PRIMARY KEY" + ",host TEXT" + ",type TEXT" + ",permission INTEGER" + ",expireType INTEGER" + ",expireTime INTEGER" + ",modificationTime INTEGER" + ",appId INTEGER" + ",isInBrowserElement INTEGER" + ")")); NS_ENSURE_SUCCESS(rv, rv); // We are guaranteed to have a moz_perms table at this point. @@ -1203,10 +1183,8 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // exist bool hostsTableExists = false; bool permsTableExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts"), - &hostsTableExists); - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_perms"), - &permsTableExists); + data->mDBConn->TableExists("moz_hosts"_ns, &hostsTableExists); + data->mDBConn->TableExists("moz_perms"_ns, &permsTableExists); MOZ_ASSERT(hostsTableExists && permsTableExists); } #endif @@ -1234,7 +1212,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // We only want to perform the re-migration if moz_hosts is a // backup bool hostsIsBackupExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts_is_backup"), + data->mDBConn->TableExists("moz_hosts_is_backup"_ns, &hostsIsBackupExists); // Only perform this migration if the original schema version was @@ -1242,7 +1220,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, if (dbSchemaVersion == 7 && hostsIsBackupExists) { nsCOMPtr stmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT host, type, permission, expireType, " "expireTime, " "modificationTime, isInBrowserElement FROM moz_hosts"), @@ -1251,8 +1229,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, nsCOMPtr idStmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT MAX(id) FROM moz_hosts"), - getter_AddRefs(idStmt)); + "SELECT MAX(id) FROM moz_hosts"_ns, getter_AddRefs(idStmt)); int64_t id = 0; bool hasResult = false; @@ -1311,19 +1288,18 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // We only want to clear out the old table if it is a backup. If // it isn't a backup, we don't need to touch it. bool hostsIsBackupExists = false; - data->mDBConn->TableExists(NS_LITERAL_CSTRING("moz_hosts_is_backup"), + data->mDBConn->TableExists("moz_hosts_is_backup"_ns, &hostsIsBackupExists); if (hostsIsBackupExists) { // Delete everything from the backup, we want to keep around the // table so that you can still downgrade and not break things, // but we don't need to keep the rows around. - rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_hosts")); + rv = data->mDBConn->ExecuteSimpleSQL("DELETE FROM moz_hosts"_ns); NS_ENSURE_SUCCESS(rv, rv); // The table is no longer a backup, so get rid of it. rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_hosts_is_backup")); + "DROP TABLE moz_hosts_is_backup"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -1346,7 +1322,7 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // Filter out the rows with storage access API permissions with a // granted origin, and remove the granted origin part from the // permission type. - rv = data->mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = data->mDBConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_perms " "SET type=SUBSTR(type, 0, INSTR(SUBSTR(type, INSTR(type, " "'^') + " @@ -1376,15 +1352,14 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // check if all the expected columns exist nsCOMPtr stmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT origin, type, permission, " - "expireType, expireTime, " - "modificationTime FROM moz_perms"), + nsLiteralCString("SELECT origin, type, permission, " + "expireType, expireTime, " + "modificationTime FROM moz_perms"), getter_AddRefs(stmt)); if (NS_SUCCEEDED(rv)) break; // our columns aren't there - drop the table! - rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_perms")); + rv = data->mDBConn->ExecuteSimpleSQL("DROP TABLE moz_perms"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = CreateTable(); @@ -1396,23 +1371,22 @@ nsresult PermissionManager::TryInitDB(bool aRemoveFile, // cache frequently used statements (for insertion, deletion, and // updating) rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO moz_perms " - "(id, origin, type, permission, expireType, " - "expireTime, modificationTime) " - "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"), + nsLiteralCString("INSERT INTO moz_perms " + "(id, origin, type, permission, expireType, " + "expireTime, modificationTime) " + "VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"), getter_AddRefs(data->mStmtInsert)); NS_ENSURE_SUCCESS(rv, rv); - rv = - data->mDBConn->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_perms " - "WHERE id = ?1"), - getter_AddRefs(data->mStmtDelete)); + rv = data->mDBConn->CreateStatement(nsLiteralCString("DELETE FROM moz_perms " + "WHERE id = ?1"), + getter_AddRefs(data->mStmtDelete)); NS_ENSURE_SUCCESS(rv, rv); rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("UPDATE moz_perms " - "SET permission = ?2, expireType= ?3, expireTime = " - "?4, modificationTime = ?5 WHERE id = ?1"), + nsLiteralCString("UPDATE moz_perms " + "SET permission = ?2, expireType= ?3, expireTime = " + "?4, modificationTime = ?5 WHERE id = ?1"), getter_AddRefs(data->mStmtUpdate)); NS_ENSURE_SUCCESS(rv, rv); @@ -1466,8 +1440,8 @@ void PermissionManager::PerformIdleDailyMaintenance() { nsCOMPtr stmtDeleteExpired; nsresult rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_perms WHERE expireType = " - "?1 AND expireTime <= ?2"), + nsLiteralCString("DELETE FROM moz_perms WHERE expireType = " + "?1 AND expireTime <= ?2"), getter_AddRefs(stmtDeleteExpired)); NS_ENSURE_SUCCESS_VOID(rv); @@ -1496,30 +1470,30 @@ nsresult PermissionManager::CreateTable() { // SQL also lives in automation.py.in. If you change this SQL change that // one too rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_perms (" - " id INTEGER PRIMARY KEY" - ",origin TEXT" - ",type TEXT" - ",permission INTEGER" - ",expireType INTEGER" - ",expireTime INTEGER" - ",modificationTime INTEGER" - ")")); + nsLiteralCString("CREATE TABLE moz_perms (" + " id INTEGER PRIMARY KEY" + ",origin TEXT" + ",type TEXT" + ",permission INTEGER" + ",expireType INTEGER" + ",expireTime INTEGER" + ",modificationTime INTEGER" + ")")); if (NS_FAILED(rv)) return rv; // We also create a legacy V4 table, for backwards compatability, // and to ensure that downgrades don't trigger a schema version change. return data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_hosts (" - " id INTEGER PRIMARY KEY" - ",host TEXT" - ",type TEXT" - ",permission INTEGER" - ",expireType INTEGER" - ",expireTime INTEGER" - ",modificationTime INTEGER" - ",isInBrowserElement INTEGER" - ")")); + nsLiteralCString("CREATE TABLE moz_hosts (" + " id INTEGER PRIMARY KEY" + ",host TEXT" + ",type TEXT" + ",permission INTEGER" + ",expireType INTEGER" + ",expireTime INTEGER" + ",modificationTime INTEGER" + ",isInBrowserElement INTEGER" + ")")); } // Returns whether the given combination of expire type and expire time are @@ -2097,8 +2071,8 @@ nsresult PermissionManager::RemoveAllInternal(bool aNotifyObservers) { } // clear the db - nsresult rv = data->mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_perms")); + nsresult rv = + data->mDBConn->ExecuteSimpleSQL("DELETE FROM moz_perms"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { NS_DispatchToMainThread(NS_NewRunnableFunction( "PermissionManager::RemoveAllInternal-Failure", @@ -2244,7 +2218,7 @@ nsresult PermissionManager::CommonTestPermissionInternal( NS_IMETHODIMP PermissionManager::GetAll( nsTArray>& aResult) { - return GetAllWithTypePrefix(NS_LITERAL_CSTRING(""), aResult); + return GetAllWithTypePrefix(""_ns, aResult); } NS_IMETHODIMP PermissionManager::GetAllWithTypePrefix( @@ -2692,7 +2666,7 @@ nsresult PermissionManager::Read(const MonitorAutoLock& aProofOfLock) { nsCOMPtr stmt; rv = data->mDBConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id, origin, type, permission, expireType, " "expireTime, modificationTime " "FROM moz_perms WHERE expireType != ?1 OR expireTime > ?2"), @@ -3050,9 +3024,9 @@ void PermissionManager::GetKeyForOrigin(const nsACString& aOrigin, // scheme in the case where they are one of these interesting URIs. We don't // want to actually parse the URL here however, because this can be called on // hot paths. - if (!StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("http:")) && - !StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("https:")) && - !StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("ftp:"))) { + if (!StringBeginsWith(aOrigin, "http:"_ns) && + !StringBeginsWith(aOrigin, "https:"_ns) && + !StringBeginsWith(aOrigin, "ftp:"_ns)) { return; } diff --git a/extensions/permissions/test/gtest/PermissionManagerTest.cpp b/extensions/permissions/test/gtest/PermissionManagerTest.cpp index c8c77f687e10..29afa117b9d3 100644 --- a/extensions/permissions/test/gtest/PermissionManagerTest.cpp +++ b/extensions/permissions/test/gtest/PermissionManagerTest.cpp @@ -17,14 +17,13 @@ using namespace mozilla; class PermissionManagerTester : public ::testing::Test { protected: PermissionManagerTester() - : mNonExistentType( - NS_LITERAL_CSTRING("permissionTypeThatIsGuaranteedToNeverExist")) {} + : mNonExistentType("permissionTypeThatIsGuaranteedToNeverExist"_ns) {} void SetUp() override { mPermissionManager = PermissionManager::GetInstance(); nsCOMPtr uri; - nsresult rv = NS_NewURI( - getter_AddRefs(uri), - NS_LITERAL_CSTRING("https://test.origin.with.subdomains.example.com")); + nsresult rv = + NS_NewURI(getter_AddRefs(uri), + "https://test.origin.with.subdomains.example.com"_ns); MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); mPrincipal = mozilla::BasePrincipal::CreateContentPrincipal(uri, OriginAttributes()); diff --git a/extensions/pref/autoconfig/src/nsAutoConfig.cpp b/extensions/pref/autoconfig/src/nsAutoConfig.cpp index b7b1fbe7a5f4..e75c77430540 100644 --- a/extensions/pref/autoconfig/src/nsAutoConfig.cpp +++ b/extensions/pref/autoconfig/src/nsAutoConfig.cpp @@ -337,7 +337,7 @@ nsresult nsAutoConfig::readOfflineFile() { getter_AddRefs(failoverFile)); if (NS_FAILED(rv)) return rv; - failoverFile->AppendNative(NS_LITERAL_CSTRING("failover.jsc")); + failoverFile->AppendNative("failover.jsc"_ns); rv = evaluateLocalFile(failoverFile); if (NS_FAILED(rv)) NS_WARNING("Couldn't open failover.jsc, going back to default prefs"); @@ -377,7 +377,7 @@ nsresult nsAutoConfig::writeFailoverFile() { getter_AddRefs(failoverFile)); if (NS_FAILED(rv)) return rv; - failoverFile->AppendNative(NS_LITERAL_CSTRING("failover.jsc")); + failoverFile->AppendNative("failover.jsc"_ns); rv = NS_NewLocalFileOutputStream(getter_AddRefs(outStr), failoverFile); if (NS_FAILED(rv)) return rv; @@ -400,16 +400,14 @@ nsresult nsAutoConfig::getEmailAddr(nsACString& emailAddr) { rv = mPrefBranch->GetCharPref("mail.accountmanager.defaultaccount", prefValue); if (NS_SUCCEEDED(rv) && !prefValue.IsEmpty()) { - emailAddr = NS_LITERAL_CSTRING("mail.account.") + prefValue + - NS_LITERAL_CSTRING(".identities"); + emailAddr = "mail.account."_ns + prefValue + ".identities"_ns; rv = mPrefBranch->GetCharPref(PromiseFlatCString(emailAddr).get(), prefValue); if (NS_FAILED(rv) || prefValue.IsEmpty()) return PromptForEMailAddress(emailAddr); int32_t commandIndex = prefValue.FindChar(','); if (commandIndex != kNotFound) prefValue.Truncate(commandIndex); - emailAddr = NS_LITERAL_CSTRING("mail.identity.") + prefValue + - NS_LITERAL_CSTRING(".useremail"); + emailAddr = "mail.identity."_ns + prefValue + ".useremail"_ns; rv = mPrefBranch->GetCharPref(PromiseFlatCString(emailAddr).get(), prefValue); if (NS_FAILED(rv) || prefValue.IsEmpty()) diff --git a/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp b/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp index adaef0ca0137..27412757f345 100644 --- a/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp +++ b/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp @@ -140,9 +140,9 @@ nsresult EvaluateAdminConfigScript(JS::HandleObject sandbox, convertedScript = NS_ConvertUTF8toUTF16(script); } else { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING( - "Your AutoConfig file is ASCII. Please convert it to UTF-8."), - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("autoconfig"), nullptr); + nsLiteralString( + u"Your AutoConfig file is ASCII. Please convert it to UTF-8."), + nsIScriptError::warningFlag, "autoconfig"_ns, nullptr); /* If the length is 0, the conversion failed. Fallback to ASCII */ convertedScript = NS_ConvertASCIItoUTF16(script); } diff --git a/extensions/pref/autoconfig/src/nsReadConfig.cpp b/extensions/pref/autoconfig/src/nsReadConfig.cpp index cecb763027e7..1a47cd2969f4 100644 --- a/extensions/pref/autoconfig/src/nsReadConfig.cpp +++ b/extensions/pref/autoconfig/src/nsReadConfig.cpp @@ -92,11 +92,10 @@ NS_IMETHODIMP nsReadConfig::Observe(nsISupports* aSubject, const char* aTopic, if (NS_FAILED(rv)) { if (sandboxEnabled) { nsContentUtils::ReportToConsoleNonLocalized( - NS_LITERAL_STRING("Autoconfig is sandboxed by default. See " - "https://support.mozilla.org/products/" - "firefox-enterprise for more information."), - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("autoconfig"), - nullptr); + u"Autoconfig is sandboxed by default. See " + "https://support.mozilla.org/products/" + "firefox-enterprise for more information."_ns, + nsIScriptError::warningFlag, "autoconfig"_ns, nullptr); } else { rv = DisplayError(); if (NS_FAILED(rv)) { diff --git a/extensions/spellcheck/hunspell/glue/mozHunspell.cpp b/extensions/spellcheck/hunspell/glue/mozHunspell.cpp index 1c2c99354a25..19ea35e2c126 100644 --- a/extensions/spellcheck/hunspell/glue/mozHunspell.cpp +++ b/extensions/spellcheck/hunspell/glue/mozHunspell.cpp @@ -322,7 +322,7 @@ mozHunspell::LoadDictionariesFromDir(nsIFile* aDir) { while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(file))) && file) { nsAutoString leafName; file->GetLeafName(leafName); - if (!StringEndsWith(leafName, NS_LITERAL_STRING(".dic"))) continue; + if (!StringEndsWith(leafName, u".dic"_ns)) continue; nsAutoString dict(leafName); dict.SetLength(dict.Length() - 4); // magic length of ".dic" diff --git a/extensions/spellcheck/src/mozInlineSpellChecker.cpp b/extensions/spellcheck/src/mozInlineSpellChecker.cpp index 9a3b861cc8e7..eebeed3aae5d 100644 --- a/extensions/spellcheck/src/mozInlineSpellChecker.cpp +++ b/extensions/spellcheck/src/mozInlineSpellChecker.cpp @@ -648,9 +648,9 @@ nsresult mozInlineSpellChecker::RegisterEventListeners() { if (NS_WARN_IF(!doc)) { return NS_ERROR_FAILURE; } - doc->AddEventListener(NS_LITERAL_STRING("blur"), this, true, false); - doc->AddEventListener(NS_LITERAL_STRING("click"), this, false, false); - doc->AddEventListener(NS_LITERAL_STRING("keypress"), this, false, false); + doc->AddEventListener(u"blur"_ns, this, true, false); + doc->AddEventListener(u"click"_ns, this, false, false); + doc->AddEventListener(u"keypress"_ns, this, false, false); return NS_OK; } @@ -667,9 +667,9 @@ nsresult mozInlineSpellChecker::UnregisterEventListeners() { if (NS_WARN_IF(!doc)) { return NS_ERROR_FAILURE; } - doc->RemoveEventListener(NS_LITERAL_STRING("blur"), this, true); - doc->RemoveEventListener(NS_LITERAL_STRING("click"), this, false); - doc->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, false); + doc->RemoveEventListener(u"blur"_ns, this, true); + doc->RemoveEventListener(u"click"_ns, this, false); + doc->RemoveEventListener(u"keypress"_ns, this, false); return NS_OK; } diff --git a/gfx/config/gfxConfigManager.cpp b/gfx/config/gfxConfigManager.cpp index 3721a0883712..56294f11a739 100644 --- a/gfx/config/gfxConfigManager.cpp +++ b/gfx/config/gfxConfigManager.cpp @@ -104,7 +104,7 @@ void gfxConfigManager::ConfigureFromBlocklist(long aFeature, int32_t status; if (!NS_SUCCEEDED(mGfxInfo->GetFeatureStatus(aFeature, blockId, &status))) { aFeatureState->Disable(FeatureStatus::BlockedNoGfxInfo, "gfxInfo is broken", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_GFX_INFO")); + "FEATURE_FAILURE_NO_GFX_INFO"_ns); } else { if (status != nsIGfxInfo::FEATURE_STATUS_OK) { @@ -125,7 +125,7 @@ bool gfxConfigManager::ConfigureWebRenderQualified() { if (!*mWrQualifiedOverride) { mFeatureWrQualified->Disable( FeatureStatus::BlockedOverride, "HW qualification pref override", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WR_QUALIFICATION_OVERRIDE")); + "FEATURE_FAILURE_WR_QUALIFICATION_OVERRIDE"_ns); } return guarded; } @@ -134,9 +134,9 @@ bool gfxConfigManager::ConfigureWebRenderQualified() { int32_t status; if (NS_FAILED(mGfxInfo->GetFeatureStatus(nsIGfxInfo::FEATURE_WEBRENDER, failureId, &status))) { - mFeatureWrQualified->Disable( - FeatureStatus::BlockedNoGfxInfo, "gfxInfo is broken", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WR_NO_GFX_INFO")); + mFeatureWrQualified->Disable(FeatureStatus::BlockedNoGfxInfo, + "gfxInfo is broken", + "FEATURE_FAILURE_WR_NO_GFX_INFO"_ns); return guarded; } @@ -172,9 +172,9 @@ bool gfxConfigManager::ConfigureWebRenderQualified() { bool hasBattery = false; mGfxInfo->GetHasBattery(&hasBattery); if (hasBattery && !mFeatureWrCompositor->IsEnabled()) { - mFeatureWrQualified->Disable( - FeatureStatus::Blocked, "Battery Intel requires os compositor", - NS_LITERAL_CSTRING("INTEL_BATTERY_REQUIRES_DCOMP")); + mFeatureWrQualified->Disable(FeatureStatus::Blocked, + "Battery Intel requires os compositor", + "INTEL_BATTERY_REQUIRES_DCOMP"_ns); } } @@ -182,7 +182,7 @@ bool gfxConfigManager::ConfigureWebRenderQualified() { if (maxRefreshRate > 60) { mFeatureWrQualified->Disable(FeatureStatus::Blocked, "Monitor refresh rate too high", - NS_LITERAL_CSTRING("REFRESH_RATE_TOO_HIGH")); + "REFRESH_RATE_TOO_HIGH"_ns); } } @@ -215,16 +215,16 @@ void gfxConfigManager::ConfigureWebRender() { // for avoiding a problem like Bug 1618370. // XXX Is there a better check for Bug 1618370? if (!mHwStretchingSupport && mScaledResolution) { - mFeatureWrCompositor->Disable( - FeatureStatus::Unavailable, "No hardware stretching support", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_HARDWARE_STRETCHING")); + mFeatureWrCompositor->Disable(FeatureStatus::Unavailable, + "No hardware stretching support", + "FEATURE_FAILURE_NO_HARDWARE_STRETCHING"_ns); } bool guardedByQualifiedPref = ConfigureWebRenderQualified(); - mFeatureWr->DisableByDefault( - FeatureStatus::OptIn, "WebRender is an opt-in feature", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DEFAULT_OFF")); + mFeatureWr->DisableByDefault(FeatureStatus::OptIn, + "WebRender is an opt-in feature", + "FEATURE_FAILURE_DEFAULT_OFF"_ns); // envvar works everywhere; note that we need this for testing in CI. // Prior to bug 1523788, the `prefEnabled` check was only done on Nightly, @@ -250,40 +250,38 @@ void gfxConfigManager::ConfigureWebRender() { // gfx.webrender.all, and gfx.webrender.all.qualified). if (mWrForceDisabled || (mWrEnvForceDisabled && mWrQualifiedOverride.isNothing())) { - mFeatureWr->UserDisable( - "User force-disabled WR", - NS_LITERAL_CSTRING("FEATURE_FAILURE_USER_FORCE_DISABLED")); + mFeatureWr->UserDisable("User force-disabled WR", + "FEATURE_FAILURE_USER_FORCE_DISABLED"_ns); } // HW_COMPOSITING being disabled implies interfacing with the GPU might break if (!mFeatureHwCompositing->IsEnabled()) { - mFeatureWr->ForceDisable( - FeatureStatus::UnavailableNoHwCompositing, - "Hardware compositing is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBRENDER_NEED_HWCOMP")); + mFeatureWr->ForceDisable(FeatureStatus::UnavailableNoHwCompositing, + "Hardware compositing is disabled", + "FEATURE_FAILURE_WEBRENDER_NEED_HWCOMP"_ns); } if (mSafeMode) { mFeatureWr->ForceDisable(FeatureStatus::UnavailableInSafeMode, "Safe-mode is enabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_SAFE_MODE")); + "FEATURE_FAILURE_SAFE_MODE"_ns); } - mFeatureWrAngle->DisableByDefault( - FeatureStatus::OptIn, "WebRender ANGLE is an opt-in feature", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DEFAULT_OFF")); + mFeatureWrAngle->DisableByDefault(FeatureStatus::OptIn, + "WebRender ANGLE is an opt-in feature", + "FEATURE_FAILURE_DEFAULT_OFF"_ns); if (mFeatureD3D11HwAngle && mWrForceAngle) { if (!mFeatureD3D11HwAngle->IsEnabled()) { - mFeatureWr->ForceDisable( - FeatureStatus::UnavailableNoAngle, "ANGLE is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_ANGLE_DISABLED")); + mFeatureWr->ForceDisable(FeatureStatus::UnavailableNoAngle, + "ANGLE is disabled", + "FEATURE_FAILURE_ANGLE_DISABLED"_ns); } else if (!mFeatureGPUProcess->IsEnabled() && (!mIsNightly || !mWrForceAngleNoGPUProcess)) { // WebRender with ANGLE relies on the GPU process when on Windows - mFeatureWr->ForceDisable( - FeatureStatus::UnavailableNoGpuProcess, "GPU Process is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_GPU_PROCESS_DISABLED")); + mFeatureWr->ForceDisable(FeatureStatus::UnavailableNoGpuProcess, + "GPU Process is disabled", + "FEATURE_FAILURE_GPU_PROCESS_DISABLED"_ns); } else if (mFeatureWr->IsEnabled()) { mFeatureWrAngle->UserEnable("Enabled"); } @@ -312,7 +310,7 @@ void gfxConfigManager::ConfigureWebRender() { mFeatureWrDComp->DisableByDefault( FeatureStatus::OptIn, "WebRender DirectComposition is an opt-in feature", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DEFAULT_OFF")); + "FEATURE_FAILURE_DEFAULT_OFF"_ns); if (mWrDCompWinEnabled) { // XXX relax win version to windows 8. @@ -325,13 +323,13 @@ void gfxConfigManager::ConfigureWebRender() { if (!mWrPictureCaching) { mFeatureWrCompositor->ForceDisable( FeatureStatus::Unavailable, "Picture caching is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_PICTURE_CACHING_DISABLED")); + "FEATURE_FAILURE_PICTURE_CACHING_DISABLED"_ns); } if (!mFeatureWrDComp->IsEnabled() && mWrCompositorDCompRequired) { mFeatureWrCompositor->ForceDisable( FeatureStatus::Unavailable, "No DirectComposition usage", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_DIRECTCOMPOSITION")); + "FEATURE_FAILURE_NO_DIRECTCOMPOSITION"_ns); } // Initialize WebRender partial present config. @@ -342,7 +340,7 @@ void gfxConfigManager::ConfigureWebRender() { if (!mWrPictureCaching) { mFeatureWrPartial->ForceDisable( FeatureStatus::Unavailable, "Picture caching is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_PICTURE_CACHING_DISABLED")); + "FEATURE_FAILURE_PICTURE_CACHING_DISABLED"_ns); } } } diff --git a/gfx/config/gfxFeature.cpp b/gfx/config/gfxFeature.cpp index d3031922d6f7..e677b674d41e 100644 --- a/gfx/config/gfxFeature.cpp +++ b/gfx/config/gfxFeature.cpp @@ -41,7 +41,7 @@ bool FeatureState::SetDefault(bool aEnable, FeatureStatus aDisableStatus, const char* aDisableMessage) { if (!aEnable) { DisableByDefault(aDisableStatus, aDisableMessage, - NS_LITERAL_CSTRING("FEATURE_FAILURE_DISABLED")); + "FEATURE_FAILURE_DISABLED"_ns); return false; } EnableByDefault(); @@ -64,8 +64,7 @@ void FeatureState::SetDefaultFromPref(const char* aPrefName, bool aIsEnablePref, } else { nsCString message("Disabled via "); message.AppendASCII(aPrefName); - UserDisable(message.get(), - NS_LITERAL_CSTRING("FEATURE_FAILURE_PREF_OFF")); + UserDisable(message.get(), "FEATURE_FAILURE_PREF_OFF"_ns); } } } diff --git a/gfx/gl/GLContext.cpp b/gfx/gl/GLContext.cpp index 313bfcea668e..f644641c4b05 100644 --- a/gfx/gl/GLContext.cpp +++ b/gfx/gl/GLContext.cpp @@ -1461,22 +1461,22 @@ void GLContext::DebugCallback(GLenum source, GLenum type, GLuint id, nsAutoCString sourceStr; switch (source) { case LOCAL_GL_DEBUG_SOURCE_API: - sourceStr = NS_LITERAL_CSTRING("SOURCE_API"); + sourceStr = "SOURCE_API"_ns; break; case LOCAL_GL_DEBUG_SOURCE_WINDOW_SYSTEM: - sourceStr = NS_LITERAL_CSTRING("SOURCE_WINDOW_SYSTEM"); + sourceStr = "SOURCE_WINDOW_SYSTEM"_ns; break; case LOCAL_GL_DEBUG_SOURCE_SHADER_COMPILER: - sourceStr = NS_LITERAL_CSTRING("SOURCE_SHADER_COMPILER"); + sourceStr = "SOURCE_SHADER_COMPILER"_ns; break; case LOCAL_GL_DEBUG_SOURCE_THIRD_PARTY: - sourceStr = NS_LITERAL_CSTRING("SOURCE_THIRD_PARTY"); + sourceStr = "SOURCE_THIRD_PARTY"_ns; break; case LOCAL_GL_DEBUG_SOURCE_APPLICATION: - sourceStr = NS_LITERAL_CSTRING("SOURCE_APPLICATION"); + sourceStr = "SOURCE_APPLICATION"_ns; break; case LOCAL_GL_DEBUG_SOURCE_OTHER: - sourceStr = NS_LITERAL_CSTRING("SOURCE_OTHER"); + sourceStr = "SOURCE_OTHER"_ns; break; default: sourceStr = nsPrintfCString("", source); @@ -1486,25 +1486,25 @@ void GLContext::DebugCallback(GLenum source, GLenum type, GLuint id, nsAutoCString typeStr; switch (type) { case LOCAL_GL_DEBUG_TYPE_ERROR: - typeStr = NS_LITERAL_CSTRING("TYPE_ERROR"); + typeStr = "TYPE_ERROR"_ns; break; case LOCAL_GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: - typeStr = NS_LITERAL_CSTRING("TYPE_DEPRECATED_BEHAVIOR"); + typeStr = "TYPE_DEPRECATED_BEHAVIOR"_ns; break; case LOCAL_GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: - typeStr = NS_LITERAL_CSTRING("TYPE_UNDEFINED_BEHAVIOR"); + typeStr = "TYPE_UNDEFINED_BEHAVIOR"_ns; break; case LOCAL_GL_DEBUG_TYPE_PORTABILITY: - typeStr = NS_LITERAL_CSTRING("TYPE_PORTABILITY"); + typeStr = "TYPE_PORTABILITY"_ns; break; case LOCAL_GL_DEBUG_TYPE_PERFORMANCE: - typeStr = NS_LITERAL_CSTRING("TYPE_PERFORMANCE"); + typeStr = "TYPE_PERFORMANCE"_ns; break; case LOCAL_GL_DEBUG_TYPE_OTHER: - typeStr = NS_LITERAL_CSTRING("TYPE_OTHER"); + typeStr = "TYPE_OTHER"_ns; break; case LOCAL_GL_DEBUG_TYPE_MARKER: - typeStr = NS_LITERAL_CSTRING("TYPE_MARKER"); + typeStr = "TYPE_MARKER"_ns; break; default: typeStr = nsPrintfCString("", type); @@ -1514,16 +1514,16 @@ void GLContext::DebugCallback(GLenum source, GLenum type, GLuint id, nsAutoCString sevStr; switch (severity) { case LOCAL_GL_DEBUG_SEVERITY_HIGH: - sevStr = NS_LITERAL_CSTRING("SEVERITY_HIGH"); + sevStr = "SEVERITY_HIGH"_ns; break; case LOCAL_GL_DEBUG_SEVERITY_MEDIUM: - sevStr = NS_LITERAL_CSTRING("SEVERITY_MEDIUM"); + sevStr = "SEVERITY_MEDIUM"_ns; break; case LOCAL_GL_DEBUG_SEVERITY_LOW: - sevStr = NS_LITERAL_CSTRING("SEVERITY_LOW"); + sevStr = "SEVERITY_LOW"_ns; break; case LOCAL_GL_DEBUG_SEVERITY_NOTIFICATION: - sevStr = NS_LITERAL_CSTRING("SEVERITY_NOTIFICATION"); + sevStr = "SEVERITY_NOTIFICATION"_ns; break; default: sevStr = nsPrintfCString("", severity); diff --git a/gfx/gl/GLContextProviderCGL.mm b/gfx/gl/GLContextProviderCGL.mm index c5d287537f85..299702a19047 100644 --- a/gfx/gl/GLContextProviderCGL.mm +++ b/gfx/gl/GLContextProviderCGL.mm @@ -297,12 +297,12 @@ static bool IsSameGPU(CGOpenGLDisplayMask mask1, CGOpenGLDisplayMask mask2) { nsACString* const out_failureId) { auto gl = CreateOffscreenFBOContext(desc); if (!gl) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_CGL_FBO"); + *out_failureId = "FEATURE_FAILURE_CGL_FBO"_ns; return nullptr; } if (!gl->Init()) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_CGL_INIT"); + *out_failureId = "FEATURE_FAILURE_CGL_INIT"_ns; NS_WARNING("Failed during Init."); return nullptr; } diff --git a/gfx/gl/GLContextProviderEGL.cpp b/gfx/gl/GLContextProviderEGL.cpp index a91e5ef850de..802b0ac4f233 100644 --- a/gfx/gl/GLContextProviderEGL.cpp +++ b/gfx/gl/GLContextProviderEGL.cpp @@ -400,8 +400,7 @@ bool GLContextEGL::Init() { bool current = MakeCurrent(); if (!current) { - gfx::LogFailure( - NS_LITERAL_CSTRING("Couldn't get device attachments for device.")); + gfx::LogFailure("Couldn't get device attachments for device."_ns); return false; } @@ -600,7 +599,7 @@ already_AddRefed GLContextEGL::CreateGLContext( if (useGles) { if (egl->fBindAPI(LOCAL_EGL_OPENGL_ES_API) == LOCAL_EGL_FALSE) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_ES"); + *out_failureId = "FEATURE_FAILURE_EGL_ES"_ns; NS_WARNING("Failed to bind API to GLES!"); return nullptr; } @@ -612,7 +611,7 @@ already_AddRefed GLContextEGL::CreateGLContext( } } else { if (egl->fBindAPI(LOCAL_EGL_OPENGL_API) == LOCAL_EGL_FALSE) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL"); + *out_failureId = "FEATURE_FAILURE_EGL"_ns; NS_WARNING("Failed to bind API to GL!"); return nullptr; } @@ -712,7 +711,7 @@ already_AddRefed GLContextEGL::CreateGLContext( if (context) break; NS_WARNING("Failed to create EGLContext with required_attribs"); - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_CREATE"); + *out_failureId = "FEATURE_FAILURE_EGL_CREATE"_ns; return nullptr; } while (false); MOZ_ASSERT(context); @@ -720,7 +719,7 @@ already_AddRefed GLContextEGL::CreateGLContext( RefPtr glContext = new GLContextEGL(egl, desc, config, surface, context); if (!glContext->Init()) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_INIT"); + *out_failureId = "FEATURE_FAILURE_EGL_INIT"_ns; return nullptr; } @@ -1112,7 +1111,7 @@ GLContextEGL::CreateEGLPBufferOffscreenContextImpl( auto* egl = gl::GLLibraryEGL::Get(); const EGLConfig config = ChooseConfig(egl, desc, useGles); if (config == EGL_NO_CONFIG) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_NO_CONFIG"); + *out_failureId = "FEATURE_FAILURE_EGL_NO_CONFIG"_ns; NS_WARNING("Failed to find a compatible config."); return nullptr; } @@ -1133,7 +1132,7 @@ GLContextEGL::CreateEGLPBufferOffscreenContextImpl( egl, config, LOCAL_EGL_NONE, pbSize); } if (!surface) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_POT"); + *out_failureId = "FEATURE_FAILURE_EGL_POT"_ns; NS_WARNING("Failed to create PBuffer for context!"); return nullptr; } diff --git a/gfx/gl/GLContextProviderNull.cpp b/gfx/gl/GLContextProviderNull.cpp index e12c8501685f..12ae358c56ae 100644 --- a/gfx/gl/GLContextProviderNull.cpp +++ b/gfx/gl/GLContextProviderNull.cpp @@ -23,7 +23,7 @@ already_AddRefed GLContextProviderNull::CreateWrappingExisting( already_AddRefed GLContextProviderNull::CreateHeadless( const GLContextCreateDesc&, nsACString* const out_failureId) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_NULL"); + *out_failureId = "FEATURE_FAILURE_NULL"_ns; return nullptr; } diff --git a/gfx/gl/GLLibraryEGL.cpp b/gfx/gl/GLLibraryEGL.cpp index 9acab7b6a0da..2db5b901e390 100644 --- a/gfx/gl/GLLibraryEGL.cpp +++ b/gfx/gl/GLLibraryEGL.cpp @@ -226,7 +226,7 @@ static bool IsAccelAngleSupported(const nsCOMPtr& gfxInfo, if (failureId.IsEmpty() && angleSupport != nsIGfxInfo::FEATURE_STATUS_OK) { // This shouldn't happen, if we see this it's because we've missed // some failure paths - failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_ACCL_ANGLE_NOT_OK"); + failureId = "FEATURE_FAILURE_ACCL_ANGLE_NOT_OK"_ns; } if (out_failureId->IsEmpty()) { *out_failureId = failureId; @@ -295,7 +295,7 @@ static EGLDisplay GetAndInitDisplayForAccelANGLE( if (!StaticPrefs::webgl_angle_try_d3d11()) { d3d11ANGLE.UserDisable("User disabled D3D11 ANGLE by pref", - NS_LITERAL_CSTRING("FAILURE_ID_ANGLE_PREF")); + "FAILURE_ID_ANGLE_PREF"_ns); } if (StaticPrefs::webgl_angle_force_d3d11()) { d3d11ANGLE.UserForceEnable( @@ -323,7 +323,7 @@ static EGLDisplay GetAndInitDisplayForAccelANGLE( } if (!ret && out_failureId->IsEmpty()) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_ACCL_ANGLE_NO_DISP"); + *out_failureId = "FEATURE_FAILURE_ACCL_ANGLE_NO_DISP"_ns; } return ret; @@ -395,7 +395,7 @@ bool GLLibraryEGL::DoEnsureInitialized() { bool GLLibraryEGL::DoEnsureInitialized(bool forceAccel, nsACString* const out_failureId) { if (mInitialized && !mSymbols.fTerminate) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_DESTROYED"); + *out_failureId = "FEATURE_FAILURE_EGL_DESTROYED"_ns; MOZ_ASSERT(false); return false; } @@ -433,9 +433,9 @@ bool GLLibraryEGL::DoEnsureInitialized(bool forceAccel, MOZ_ASSERT(false, "d3dcompiler DLL loading failed."); } while (false); - mGLLibrary = LoadLibraryForEGLOnWindows(NS_LITERAL_STRING("libGLESv2.dll")); + mGLLibrary = LoadLibraryForEGLOnWindows(u"libGLESv2.dll"_ns); - mEGLLibrary = LoadLibraryForEGLOnWindows(NS_LITERAL_STRING("libEGL.dll")); + mEGLLibrary = LoadLibraryForEGLOnWindows(u"libEGL.dll"_ns); } #else // !Windows @@ -476,7 +476,7 @@ bool GLLibraryEGL::DoEnsureInitialized(bool forceAccel, if (!mEGLLibrary || !mGLLibrary) { NS_WARNING("Couldn't load EGL LIB."); - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_LOAD_3"); + *out_failureId = "FEATURE_FAILURE_EGL_LOAD_3"_ns; return false; } @@ -526,7 +526,7 @@ bool GLLibraryEGL::DoEnsureInitialized(bool forceAccel, if (!libLoader.LoadSymbols(earlySymbols)) { NS_WARNING( "Couldn't find required entry points in EGL library (early init)"); - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_EGL_SYM"); + *out_failureId = "FEATURE_FAILURE_EGL_SYM"_ns; return false; } } @@ -784,7 +784,7 @@ EGLDisplay GLLibraryEGL::CreateDisplay(bool forceAccel, shouldTryWARP = true; shouldTryAccel = false; if (accelAngleFailureId.IsEmpty()) { - accelAngleFailureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_FORCE_WARP"); + accelAngleFailureId = "FEATURE_FAILURE_FORCE_WARP"_ns; } } @@ -796,16 +796,15 @@ EGLDisplay GLLibraryEGL::CreateDisplay(bool forceAccel, // Report the acceleration status to telemetry if (!chosenDisplay) { if (accelAngleFailureId.IsEmpty()) { - Telemetry::Accumulate( - Telemetry::CANVAS_WEBGL_ACCL_FAILURE_ID, - NS_LITERAL_CSTRING("FEATURE_FAILURE_ACCL_ANGLE_UNKNOWN")); + Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_ACCL_FAILURE_ID, + "FEATURE_FAILURE_ACCL_ANGLE_UNKNOWN"_ns); } else { Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_ACCL_FAILURE_ID, accelAngleFailureId); } } else { Telemetry::Accumulate(Telemetry::CANVAS_WEBGL_ACCL_FAILURE_ID, - NS_LITERAL_CSTRING("SUCCESS")); + "SUCCESS"_ns); } // Fallback to a WARP display if ANGLE fails, or if WARP is forced @@ -813,7 +812,7 @@ EGLDisplay GLLibraryEGL::CreateDisplay(bool forceAccel, chosenDisplay = GetAndInitWARPDisplay(*this, EGL_DEFAULT_DISPLAY); if (!chosenDisplay) { if (out_failureId->IsEmpty()) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_WARP_FALLBACK"); + *out_failureId = "FEATURE_FAILURE_WARP_FALLBACK"_ns; } NS_ERROR("Fallback WARP context failed to initialize."); return nullptr; @@ -838,7 +837,7 @@ EGLDisplay GLLibraryEGL::CreateDisplay(bool forceAccel, if (!chosenDisplay) { if (out_failureId->IsEmpty()) { - *out_failureId = NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_DISPLAY"); + *out_failureId = "FEATURE_FAILURE_NO_DISPLAY"_ns; } NS_WARNING("Failed to initialize a display."); return nullptr; diff --git a/gfx/ipc/GPUProcessManager.cpp b/gfx/ipc/GPUProcessManager.cpp index b1dc89f790d4..ebfc0773fc32 100644 --- a/gfx/ipc/GPUProcessManager.cpp +++ b/gfx/ipc/GPUProcessManager.cpp @@ -391,8 +391,7 @@ void GPUProcessManager::OnProcessLaunchComplete(GPUProcessHost* aHost) { mQueuedPrefs.Clear(); CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::GPUProcessStatus, - NS_LITERAL_CSTRING("Running")); + CrashReporter::Annotation::GPUProcessStatus, "Running"_ns); CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::GPUProcessLaunchCount, @@ -454,25 +453,24 @@ void GPUProcessManager::DisableWebRender(wr::WebRenderError aError) { // Disable WebRender if (aError == wr::WebRenderError::INITIALIZE) { gfx::gfxConfig::GetFeature(gfx::Feature::WEBRENDER) - .ForceDisable( - gfx::FeatureStatus::Unavailable, "WebRender initialization failed", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBRENDER_INITIALIZE")); + .ForceDisable(gfx::FeatureStatus::Unavailable, + "WebRender initialization failed", + "FEATURE_FAILURE_WEBRENDER_INITIALIZE"_ns); } else if (aError == wr::WebRenderError::MAKE_CURRENT) { gfx::gfxConfig::GetFeature(gfx::Feature::WEBRENDER) - .ForceDisable( - gfx::FeatureStatus::Unavailable, - "Failed to make render context current", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBRENDER_MAKE_CURRENT")); + .ForceDisable(gfx::FeatureStatus::Unavailable, + "Failed to make render context current", + "FEATURE_FAILURE_WEBRENDER_MAKE_CURRENT"_ns); } else if (aError == wr::WebRenderError::RENDER) { gfx::gfxConfig::GetFeature(gfx::Feature::WEBRENDER) .ForceDisable(gfx::FeatureStatus::Unavailable, "Failed to render WebRender", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBRENDER_RENDER")); + "FEATURE_FAILURE_WEBRENDER_RENDER"_ns); } else if (aError == wr::WebRenderError::NEW_SURFACE) { gfx::gfxConfig::GetFeature(gfx::Feature::WEBRENDER) - .ForceDisable( - gfx::FeatureStatus::Unavailable, "Failed to create new surface", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WEBRENDER_NEW_SURFACE")); + .ForceDisable(gfx::FeatureStatus::Unavailable, + "Failed to create new surface", + "FEATURE_FAILURE_WEBRENDER_NEW_SURFACE"_ns); } else { MOZ_ASSERT_UNREACHABLE("Invalid value"); } @@ -742,8 +740,7 @@ void GPUProcessManager::DestroyProcess() { } CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::GPUProcessStatus, - NS_LITERAL_CSTRING("Destroyed")); + CrashReporter::Annotation::GPUProcessStatus, "Destroyed"_ns); } already_AddRefed GPUProcessManager::CreateTopLevelCompositor( diff --git a/gfx/layers/MemoryPressureObserver.cpp b/gfx/layers/MemoryPressureObserver.cpp index 6883bdf58cea..16c9ea4b1eef 100644 --- a/gfx/layers/MemoryPressureObserver.cpp +++ b/gfx/layers/MemoryPressureObserver.cpp @@ -60,11 +60,9 @@ MemoryPressureObserver::Observe(nsISupports* aSubject, const char* aTopic, if (mListener && strcmp(aTopic, "memory-pressure") == 0) { MemoryPressureReason reason = MemoryPressureReason::LOW_MEMORY; auto reason_string = nsDependentString(aData); - if (StringBeginsWith(reason_string, - NS_LITERAL_STRING("low-memory-ongoing"))) { + if (StringBeginsWith(reason_string, u"low-memory-ongoing"_ns)) { reason = MemoryPressureReason::LOW_MEMORY_ONGOING; - } else if (StringBeginsWith(reason_string, - NS_LITERAL_STRING("heap-minimize"))) { + } else if (StringBeginsWith(reason_string, u"heap-minimize"_ns)) { reason = MemoryPressureReason::HEAP_MINIMIZE; } mListener->OnMemoryPressure(reason); diff --git a/gfx/layers/PaintThread.cpp b/gfx/layers/PaintThread.cpp index 18d7feec4562..019dbc858b68 100644 --- a/gfx/layers/PaintThread.cpp +++ b/gfx/layers/PaintThread.cpp @@ -121,8 +121,7 @@ void PaintThread::InitPaintWorkers() { MOZ_ASSERT(NS_IsMainThread()); int32_t count = PaintThread::CalculatePaintWorkerCount(); if (count != 1) { - mPaintWorkers = - SharedThreadPool::Get(NS_LITERAL_CSTRING("PaintWorker"), count); + mPaintWorkers = SharedThreadPool::Get("PaintWorker"_ns, count); mPaintWorkers->SetThreadStackSize(GetPaintThreadStackSize()); } } diff --git a/gfx/layers/ProfilerScreenshots.cpp b/gfx/layers/ProfilerScreenshots.cpp index 8eadbe0937d5..a6f602d26f84 100644 --- a/gfx/layers/ProfilerScreenshots.cpp +++ b/gfx/layers/ProfilerScreenshots.cpp @@ -80,8 +80,8 @@ void ProfilerScreenshots::SubmitScreenshot( // Encode surf to a JPEG data URL. nsCString dataURL; nsresult rv = gfxUtils::EncodeSourceSurface( - surf, ImageType::JPEG, NS_LITERAL_STRING("quality=85"), - gfxUtils::eDataURIEncode, nullptr, &dataURL); + surf, ImageType::JPEG, u"quality=85"_ns, gfxUtils::eDataURIEncode, + nullptr, &dataURL); if (NS_SUCCEEDED(rv)) { // Add a marker with the data URL. AUTO_PROFILER_STATS(add_marker_with_ScreenshotPayload); diff --git a/gfx/layers/apz/src/AsyncPanZoomController.cpp b/gfx/layers/apz/src/AsyncPanZoomController.cpp index 1553418d5ccc..2a6165912274 100644 --- a/gfx/layers/apz/src/AsyncPanZoomController.cpp +++ b/gfx/layers/apz/src/AsyncPanZoomController.cpp @@ -2341,8 +2341,8 @@ nsEventStatus AsyncPanZoomController::OnScrollWheel( StaticPrefs::test_mousescroll()) { if (RefPtr controller = GetGeckoContentController()) { - controller->NotifyMozMouseScrollEvent( - GetScrollId(), NS_LITERAL_STRING("MozMouseScrollFailed")); + controller->NotifyMozMouseScrollEvent(GetScrollId(), + u"MozMouseScrollFailed"_ns); } } return nsEventStatus_eConsumeNoDefault; diff --git a/gfx/layers/apz/src/InputBlockState.cpp b/gfx/layers/apz/src/InputBlockState.cpp index 501674b65c32..08841ecf39e0 100644 --- a/gfx/layers/apz/src/InputBlockState.cpp +++ b/gfx/layers/apz/src/InputBlockState.cpp @@ -435,8 +435,7 @@ bool WheelBlockState::MaybeTimeout(const TimeStamp& aTimeStamp) { if (StaticPrefs::test_mousescroll()) { RefPtr apzc = GetTargetApzc(); - apzc->NotifyMozMouseScrollEvent( - NS_LITERAL_STRING("MozMouseScrollTransactionTimeout")); + apzc->NotifyMozMouseScrollEvent(u"MozMouseScrollTransactionTimeout"_ns); } EndTransaction(); diff --git a/gfx/layers/apz/util/APZEventState.cpp b/gfx/layers/apz/util/APZEventState.cpp index b339e2cde4c8..78fcdf4bce36 100644 --- a/gfx/layers/apz/util/APZEventState.cpp +++ b/gfx/layers/apz/util/APZEventState.cpp @@ -222,7 +222,7 @@ bool APZEventState::FireContextmenuEvents(PresShell* aPresShell, CSSPoint point = CSSPoint::FromAppUnits( ViewportUtils::VisualToLayout(CSSPoint::ToAppUnits(aPoint), aPresShell)); bool eventHandled = APZCCallbackHelper::DispatchMouseEvent( - aPresShell, NS_LITERAL_STRING("contextmenu"), point, 2, 1, + aPresShell, u"contextmenu"_ns, point, 2, 1, WidgetModifiersToDOMModifiers(aModifiers), dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH, 0 /* Use the default value here. */); diff --git a/gfx/layers/composite/FPSCounter.cpp b/gfx/layers/composite/FPSCounter.cpp index 3ea55482dcbe..cf3d0725edc8 100644 --- a/gfx/layers/composite/FPSCounter.cpp +++ b/gfx/layers/composite/FPSCounter.cpp @@ -320,9 +320,9 @@ nsresult FPSCounter::WriteFrameTimeStamps() { NS_ENSURE_SUCCESS(rv, rv); if (!strncmp(mFPSName, "Compositor", strlen(mFPSName))) { - resultFile->Append(NS_LITERAL_STRING("fps.txt")); + resultFile->Append(u"fps.txt"_ns); } else { - resultFile->Append(NS_LITERAL_STRING("txn.txt")); + resultFile->Append(u"txn.txt"_ns); } PRFileDesc* fd = nullptr; diff --git a/gfx/layers/d3d11/CompositorD3D11.cpp b/gfx/layers/d3d11/CompositorD3D11.cpp index 91daa036969b..5835983189ea 100644 --- a/gfx/layers/d3d11/CompositorD3D11.cpp +++ b/gfx/layers/d3d11/CompositorD3D11.cpp @@ -168,9 +168,8 @@ bool CompositorD3D11::Initialize(nsCString* const out_failureReason) { } if (!mAttachments || !mAttachments->IsValid()) { gfxCriticalNote << "[D3D11] failed to get compositor device attachments"; - *out_failureReason = - mAttachments ? mAttachments->GetFailureId() - : NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_ATTACHMENTS"); + *out_failureReason = mAttachments ? mAttachments->GetFailureId() + : "FEATURE_FAILURE_NO_ATTACHMENTS"_ns; return false; } diff --git a/gfx/layers/d3d11/MLGDeviceD3D11.cpp b/gfx/layers/d3d11/MLGDeviceD3D11.cpp index 79816b919eee..d30430f3de17 100644 --- a/gfx/layers/d3d11/MLGDeviceD3D11.cpp +++ b/gfx/layers/d3d11/MLGDeviceD3D11.cpp @@ -1846,7 +1846,7 @@ void MLGDeviceD3D11::HandleDeviceReset(const char* aWhere) { return; } - Fail(NS_LITERAL_CSTRING("FEATURE_FAILURE_DEVICE_RESET"), nullptr); + Fail("FEATURE_FAILURE_DEVICE_RESET"_ns, nullptr); gfxCriticalNote << "GFX: D3D11 detected a device reset in " << aWhere; if (XRE_IsGPUProcess()) { diff --git a/gfx/layers/ipc/CanvasThread.cpp b/gfx/layers/ipc/CanvasThread.cpp index f3f0ac2a92c9..640229210363 100644 --- a/gfx/layers/ipc/CanvasThread.cpp +++ b/gfx/layers/ipc/CanvasThread.cpp @@ -56,7 +56,7 @@ already_AddRefed CanvasThreadHolder::EnsureCanvasThread() { // manage the load between them. uint32_t threadLimit = std::max(2, PR_GetNumberOfProcessors() / 2); nsCOMPtr canvasWorkers = - SharedThreadPool::Get(NS_LITERAL_CSTRING("CanvasWorkers"), threadLimit); + SharedThreadPool::Get("CanvasWorkers"_ns, threadLimit); if (!canvasWorkers) { return nullptr; } diff --git a/gfx/layers/opengl/CompositorOGL.cpp b/gfx/layers/opengl/CompositorOGL.cpp index b15f85713a91..81d6b8fbbf3e 100644 --- a/gfx/layers/opengl/CompositorOGL.cpp +++ b/gfx/layers/opengl/CompositorOGL.cpp @@ -516,21 +516,21 @@ bool CompositorOGL::Initialize(nsCString* const out_failureReason) { if (console) { nsString msg; - msg += NS_LITERAL_STRING( - "OpenGL compositor Initialized Succesfully.\nVersion: "); + msg += nsLiteralString( + u"OpenGL compositor Initialized Succesfully.\nVersion: "); msg += NS_ConvertUTF8toUTF16(nsDependentCString( (const char*)mGLContext->fGetString(LOCAL_GL_VERSION))); - msg += NS_LITERAL_STRING("\nVendor: "); + msg += u"\nVendor: "_ns; msg += NS_ConvertUTF8toUTF16(nsDependentCString( (const char*)mGLContext->fGetString(LOCAL_GL_VENDOR))); - msg += NS_LITERAL_STRING("\nRenderer: "); + msg += u"\nRenderer: "_ns; msg += NS_ConvertUTF8toUTF16(nsDependentCString( (const char*)mGLContext->fGetString(LOCAL_GL_RENDERER))); - msg += NS_LITERAL_STRING("\nFBO Texture Target: "); + msg += u"\nFBO Texture Target: "_ns; if (mFBOTextureTarget == LOCAL_GL_TEXTURE_2D) - msg += NS_LITERAL_STRING("TEXTURE_2D"); + msg += u"TEXTURE_2D"_ns; else - msg += NS_LITERAL_STRING("TEXTURE_RECTANGLE"); + msg += u"TEXTURE_RECTANGLE"_ns; console->LogStringMessage(msg.get()); } diff --git a/gfx/thebes/DeviceManagerDx.cpp b/gfx/thebes/DeviceManagerDx.cpp index 07da4f2bcc48..b1b4b1be272d 100644 --- a/gfx/thebes/DeviceManagerDx.cpp +++ b/gfx/thebes/DeviceManagerDx.cpp @@ -86,7 +86,7 @@ bool DeviceManagerDx::LoadD3D11() { if (!module) { d3d11.SetFailed(FeatureStatus::Unavailable, "Direct3D11 not available on this computer", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_LIB")); + "FEATURE_FAILURE_D3D11_LIB"_ns); return false; } @@ -96,7 +96,7 @@ bool DeviceManagerDx::LoadD3D11() { // We should just be on Windows Vista or XP in this case. d3d11.SetFailed(FeatureStatus::Unavailable, "Direct3D11 not available on this computer", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_FUNCPTR")); + "FEATURE_FAILURE_D3D11_FUNCPTR"_ns); return false; } @@ -268,8 +268,7 @@ bool DeviceManagerDx::CreateCompositorDevices() { // Sync Advanced-Layers with D3D11. if (gfxConfig::IsEnabled(Feature::ADVANCED_LAYERS)) { gfxConfig::SetFailed(Feature::ADVANCED_LAYERS, FeatureStatus::Unavailable, - "Requires D3D11", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_D3D11")); + "Requires D3D11", "FEATURE_FAILURE_NO_D3D11"_ns); } return false; } @@ -519,7 +518,7 @@ bool DeviceManagerDx::CreateCompositorDeviceHelper( if (StaticPrefs::gfx_testing_device_fail()) { aD3d11.SetFailed(FeatureStatus::Failed, "Direct3D11 device failure simulated by preference", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_SIM")); + "FEATURE_FAILURE_D3D11_SIM"_ns); return false; } @@ -546,7 +545,7 @@ bool DeviceManagerDx::CreateCompositorDeviceHelper( gfxCriticalError() << "Crash during D3D11 device creation"; aD3d11.SetFailed(FeatureStatus::CrashedInHandler, "Crashed trying to acquire a D3D11 device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DEVICE1")); + "FEATURE_FAILURE_D3D11_DEVICE1"_ns); } return false; } @@ -555,7 +554,7 @@ bool DeviceManagerDx::CreateCompositorDeviceHelper( if (!aAttemptVideoSupport) { aD3d11.SetFailed(FeatureStatus::Failed, "Failed to acquire a D3D11 device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DEVICE2")); + "FEATURE_FAILURE_D3D11_DEVICE2"_ns); } return false; } @@ -563,7 +562,7 @@ bool DeviceManagerDx::CreateCompositorDeviceHelper( if (!aAttemptVideoSupport) { aD3d11.SetFailed(FeatureStatus::Broken, "Direct3D11 device was determined to be broken", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_BROKEN")); + "FEATURE_FAILURE_D3D11_BROKEN"_ns); } return false; } @@ -592,14 +591,14 @@ void DeviceManagerDx::CreateCompositorDevice(FeatureState& d3d11) { if (!adapter) { d3d11.SetFailed(FeatureStatus::Unavailable, "Failed to acquire a DXGI adapter", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DXGI")); + "FEATURE_FAILURE_D3D11_DXGI"_ns); return; } if (XRE_IsGPUProcess() && !D3D11Checks::DoesRemotePresentWork(adapter)) { d3d11.SetFailed(FeatureStatus::Unavailable, "DXGI does not support out-of-process presentation", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_REMOTE_PRESENT")); + "FEATURE_FAILURE_D3D11_REMOTE_PRESENT"_ns); return; } @@ -715,7 +714,7 @@ void DeviceManagerDx::CreateWARPCompositorDevice() { gfxCriticalError() << "Exception occurred initializing WARP D3D11 device!"; d3d11.SetFailed(FeatureStatus::CrashedInHandler, "Crashed creating a D3D11 WARP device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_WARP_DEVICE")); + "FEATURE_FAILURE_D3D11_WARP_DEVICE"_ns); } if (FAILED(hr) || !device) { @@ -724,7 +723,7 @@ void DeviceManagerDx::CreateWARPCompositorDevice() { << hexa(hr); d3d11.SetFailed(FeatureStatus::Failed, "Failed to create a D3D11 WARP device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_WARP_DEVICE2")); + "FEATURE_FAILURE_D3D11_WARP_DEVICE2"_ns); return; } @@ -941,10 +940,9 @@ void DeviceManagerDx::CreateMLGDevice() { RefPtr d3d11Device = GetCompositorDevice(); if (!d3d11Device) { - DisableAdvancedLayers( - FeatureStatus::Unavailable, - NS_LITERAL_CSTRING("Advanced-layers requires a D3D11 device"), - NS_LITERAL_CSTRING("FEATURE_FAILURE_NEED_D3D11_DEVICE")); + DisableAdvancedLayers(FeatureStatus::Unavailable, + "Advanced-layers requires a D3D11 device"_ns, + "FEATURE_FAILURE_NEED_D3D11_DEVICE"_ns); return; } @@ -1146,7 +1144,7 @@ void DeviceManagerDx::DisableD3D11AfterCrash() { gfxConfig::Disable(Feature::D3D11_COMPOSITING, FeatureStatus::CrashedInHandler, "Crashed while acquiring a Direct3D11 device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_CRASH")); + "FEATURE_FAILURE_D3D11_CRASH"_ns); ResetDevices(); } @@ -1311,7 +1309,7 @@ void DeviceManagerDx::InitializeDirectDraw() { if (!mDirectDrawDLL) { ddraw.SetFailed(FeatureStatus::Unavailable, "DirectDraw not available on this computer", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DDRAW_LIB")); + "FEATURE_FAILURE_DDRAW_LIB"_ns); return; } @@ -1320,7 +1318,7 @@ void DeviceManagerDx::InitializeDirectDraw() { if (!sDirectDrawCreateExFn) { ddraw.SetFailed(FeatureStatus::Unavailable, "DirectDraw not available on this computer", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DDRAW_LIB")); + "FEATURE_FAILURE_DDRAW_LIB"_ns); return; } @@ -1331,13 +1329,13 @@ void DeviceManagerDx::InitializeDirectDraw() { } MOZ_SEH_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { ddraw.SetFailed(FeatureStatus::Failed, "Failed to create DirectDraw", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DDRAW_LIB")); + "FEATURE_FAILURE_DDRAW_LIB"_ns); gfxCriticalNote << "DoesCreatingDirectDrawFailed"; return; } if (FAILED(hr)) { ddraw.SetFailed(FeatureStatus::Failed, "Failed to create DirectDraw", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DDRAW_LIB")); + "FEATURE_FAILURE_DDRAW_LIB"_ns); gfxCriticalNote << "DoesCreatingDirectDrawFailed " << hexa(hr); return; } diff --git a/gfx/thebes/SharedFontList.cpp b/gfx/thebes/SharedFontList.cpp index 9ba6a0d7a608..58d9796db8dc 100644 --- a/gfx/thebes/SharedFontList.cpp +++ b/gfx/thebes/SharedFontList.cpp @@ -853,10 +853,9 @@ Family* FontList::FindFamily(const nsCString& aName) { pfl->mLocalNameTable.Clear(); return nullptr; } - const nsLiteralCString kStyleSuffixes[] = { - nsLiteralCString(" book"), nsLiteralCString(" medium"), - nsLiteralCString(" normal"), nsLiteralCString(" regular"), - nsLiteralCString(" roman"), nsLiteralCString(" upright")}; + const nsLiteralCString kStyleSuffixes[] = {" book"_ns, " medium"_ns, + " normal"_ns, " regular"_ns, + " roman"_ns, " upright"_ns}; for (const auto& styleName : kStyleSuffixes) { if (StringEndsWith(aName, styleName)) { // See if we have a known family that matches the "base" family name diff --git a/gfx/thebes/gfxDWriteFontList.cpp b/gfx/thebes/gfxDWriteFontList.cpp index 856e09da4466..0bb81b1f1e0e 100644 --- a/gfx/thebes/gfxDWriteFontList.cpp +++ b/gfx/thebes/gfxDWriteFontList.cpp @@ -853,7 +853,7 @@ FontFamily gfxDWriteFontList::GetDefaultFontForPlatform( const gfxFontStyle* aStyle) { // try Arial first FontFamily ff; - ff = FindFamily(NS_LITERAL_CSTRING("Arial")); + ff = FindFamily("Arial"_ns); if (!ff.IsNull()) { return ff; } @@ -1024,7 +1024,7 @@ void gfxDWriteFontList::AppendFamiliesFromCollection( if (FAILED(hr)) { continue; } - if (faceName.Find(NS_LITERAL_CSTRING("Ultra Bold")) == kNotFound) { + if (faceName.Find("Ultra Bold"_ns) == kNotFound) { return false; } } @@ -1437,7 +1437,7 @@ nsresult gfxDWriteFontList::InitFontListForPlatform() { bool allUltraBold = true; for (i = 0; i < faces.Length(); i++) { // does the face have 'Ultra Bold' in the name? - if (faces[i]->Name().Find(NS_LITERAL_CSTRING("Ultra Bold")) == -1) { + if (faces[i]->Name().Find("Ultra Bold"_ns) == -1) { allUltraBold = false; break; } @@ -2263,7 +2263,7 @@ gfxDWriteFontList::CreateBundledFontsCollection(IDWriteFactory* aFactory) { if (NS_FAILED(rv)) { return nullptr; } - if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("fonts")))) { + if (NS_FAILED(localDir->Append(u"fonts"_ns))) { return nullptr; } bool isDir; diff --git a/gfx/thebes/gfxDWriteFonts.cpp b/gfx/thebes/gfxDWriteFonts.cpp index 27b0d255d1b1..7f7c3b20b895 100644 --- a/gfx/thebes/gfxDWriteFonts.cpp +++ b/gfx/thebes/gfxDWriteFonts.cpp @@ -130,7 +130,7 @@ bool gfxDWriteFont::GetFakeMetricsForArialBlack( style.weight = FontWeight(700); gfxFontEntry* fe = gfxPlatformFontList::PlatformFontList()->FindFontForFamily( - NS_LITERAL_CSTRING("Arial"), &style); + "Arial"_ns, &style); if (!fe || fe == mFontEntry) { return false; } diff --git a/gfx/thebes/gfxFT2FontList.cpp b/gfx/thebes/gfxFT2FontList.cpp index 7ed93b82389a..defd767d3997 100644 --- a/gfx/thebes/gfxFT2FontList.cpp +++ b/gfx/thebes/gfxFT2FontList.cpp @@ -1420,7 +1420,7 @@ void gfxFT2FontList::FindFonts() { if (androidRoot) { root = androidRoot; } else { - root = NS_LITERAL_CSTRING("/system"); + root = "/system"_ns; } root.AppendLiteral("/fonts"); @@ -1446,7 +1446,7 @@ void gfxFT2FontList::FindFonts() { nsresult rv = dirSvc->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(appDir)); if (NS_SUCCEEDED(rv)) { - appDir->AppendNative(NS_LITERAL_CSTRING("fonts")); + appDir->AppendNative("fonts"_ns); nsCString localPath; if (NS_SUCCEEDED(appDir->GetNativePath(localPath))) { FindFontsInDir(localPath, mFontNameCache.get()); @@ -1458,8 +1458,7 @@ void gfxFT2FontList::FindFonts() { nsCOMPtr localDir; nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR, getter_AddRefs(localDir)); - if (NS_SUCCEEDED(rv) && - NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("fonts")))) { + if (NS_SUCCEEDED(rv) && NS_SUCCEEDED(localDir->Append(u"fonts"_ns))) { nsCString localPath; rv = localDir->GetNativePath(localPath); if (NS_SUCCEEDED(rv)) { @@ -1755,9 +1754,9 @@ FontFamily gfxFT2FontList::GetDefaultFontForPlatform( const gfxFontStyle* aStyle) { FontFamily ff; #if defined(MOZ_WIDGET_ANDROID) - ff = FindFamily(NS_LITERAL_CSTRING("Roboto")); + ff = FindFamily("Roboto"_ns); if (ff.IsNull()) { - ff = FindFamily(NS_LITERAL_CSTRING("Droid Sans")); + ff = FindFamily("Droid Sans"_ns); } #endif /* TODO: what about Qt or other platforms that may use this? */ diff --git a/gfx/thebes/gfxFcPlatformFontList.cpp b/gfx/thebes/gfxFcPlatformFontList.cpp index f3c13c6daaca..62a807a91eff 100644 --- a/gfx/thebes/gfxFcPlatformFontList.cpp +++ b/gfx/thebes/gfxFcPlatformFontList.cpp @@ -1848,11 +1848,9 @@ void gfxFcPlatformFontList::GetFontList(nsAtom* aLangGroup, // The first in the list becomes the default in // FontBuilder.readFontSelection() if the preference-selected font is not // available, so put system configured defaults first. - if (monospace) - aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("monospace")); - if (sansSerif) - aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("sans-serif")); - if (serif) aListOfFonts.InsertElementAt(0, NS_LITERAL_STRING("serif")); + if (monospace) aListOfFonts.InsertElementAt(0, u"monospace"_ns); + if (sansSerif) aListOfFonts.InsertElementAt(0, u"sans-serif"_ns); + if (serif) aListOfFonts.InsertElementAt(0, u"serif"_ns); } FontFamily gfxFcPlatformFontList::GetDefaultFontForPlatform( @@ -1860,7 +1858,7 @@ FontFamily gfxFcPlatformFontList::GetDefaultFontForPlatform( // Get the default font by using a fake name to retrieve the first // scalable font that fontconfig suggests for the given language. PrefFontList* prefFonts = - FindGenericFamilies(NS_LITERAL_CSTRING("-moz-default"), aStyle->language); + FindGenericFamilies("-moz-default"_ns, aStyle->language); NS_ASSERTION(prefFonts, "null list of generic fonts"); if (prefFonts && !prefFonts->IsEmpty()) { return (*prefFonts)[0]; @@ -2442,7 +2440,7 @@ void gfxFcPlatformFontList::ActivateBundledFonts() { if (NS_FAILED(rv)) { return; } - if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("fonts")))) { + if (NS_FAILED(localDir->Append(u"fonts"_ns))) { return; } bool isDir; diff --git a/gfx/thebes/gfxGDIFontList.cpp b/gfx/thebes/gfxGDIFontList.cpp index ae324ab2f9ca..404a5b64c323 100644 --- a/gfx/thebes/gfxGDIFontList.cpp +++ b/gfx/thebes/gfxGDIFontList.cpp @@ -1067,7 +1067,7 @@ void gfxGDIFontList::ActivateBundledFonts() { if (NS_FAILED(rv)) { return; } - if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("fonts")))) { + if (NS_FAILED(localDir->Append(u"fonts"_ns))) { return; } bool isDir; diff --git a/gfx/thebes/gfxMacPlatformFontList.mm b/gfx/thebes/gfxMacPlatformFontList.mm index 13cfc4bee366..14c6600d03e8 100644 --- a/gfx/thebes/gfxMacPlatformFontList.mm +++ b/gfx/thebes/gfxMacPlatformFontList.mm @@ -828,7 +828,7 @@ explicit gfxSingleFaceMacFontFamily(const nsACString& aName) nsresult rv; nsCOMPtr langFonts(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { - rv = langFonts->InitWithNativePath(NS_LITERAL_CSTRING(LANG_FONTS_DIR)); + rv = langFonts->InitWithNativePath(nsLiteralCString(LANG_FONTS_DIR)); if (NS_SUCCEEDED(rv)) { ActivateFontsFromDir(langFonts); } @@ -1791,7 +1791,7 @@ virtual void Load() { if (NS_FAILED(NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(localDir)))) { return; } - if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("fonts")))) { + if (NS_FAILED(localDir->Append(u"fonts"_ns))) { return; } diff --git a/gfx/thebes/gfxPlatform.cpp b/gfx/thebes/gfxPlatform.cpp index 0b6eb95fdc2f..82014416a141 100644 --- a/gfx/thebes/gfxPlatform.cpp +++ b/gfx/thebes/gfxPlatform.cpp @@ -693,19 +693,19 @@ struct WebRenderMemoryReporterHelper { void Report(size_t aBytes, const char* aName) const { nsPrintfCString path("explicit/gfx/webrender/%s", aName); - nsCString desc(NS_LITERAL_CSTRING("CPU heap memory used by WebRender")); + nsCString desc("CPU heap memory used by WebRender"_ns); ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_HEAP); } void ReportTexture(size_t aBytes, const char* aName) const { nsPrintfCString path("gfx/webrender/textures/%s", aName); - nsCString desc(NS_LITERAL_CSTRING("GPU texture memory used by WebRender")); + nsCString desc("GPU texture memory used by WebRender"_ns); ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_OTHER); } void ReportTotalGPUBytes(size_t aBytes) const { - nsCString path(NS_LITERAL_CSTRING("gfx/webrender/total-gpu-bytes")); - nsCString desc(NS_LITERAL_CSTRING( + nsCString path("gfx/webrender/total-gpu-bytes"_ns); + nsCString desc(nsLiteralCString( "Total GPU bytes used by WebRender (should match textures/ sum)")); ReportInternal(aBytes, path, desc, nsIMemoryReporter::KIND_OTHER); } @@ -2597,7 +2597,7 @@ void gfxPlatform::InitGPUProcessPrefs() { if (!BrowserTabsRemoteAutostart()) { gpuProc.DisableByDefault(FeatureStatus::Unavailable, "Multi-process mode is not enabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_E10S")); + "FEATURE_FAILURE_NO_E10S"_ns); } else { gpuProc.SetDefaultFromPref( StaticPrefs::GetPrefName_layers_gpu_process_enabled(), true, @@ -2610,18 +2610,18 @@ void gfxPlatform::InitGPUProcessPrefs() { if (IsHeadless()) { gpuProc.ForceDisable(FeatureStatus::Blocked, "Headless mode is enabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_HEADLESS_MODE")); + "FEATURE_FAILURE_HEADLESS_MODE"_ns); return; } if (InSafeMode()) { gpuProc.ForceDisable(FeatureStatus::Blocked, "Safe-mode is enabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_SAFE_MODE")); + "FEATURE_FAILURE_SAFE_MODE"_ns); return; } if (StaticPrefs::gfx_layerscope_enabled()) { gpuProc.ForceDisable(FeatureStatus::Blocked, "LayerScope does not work in the GPU process", - NS_LITERAL_CSTRING("FEATURE_FAILURE_LAYERSCOPE")); + "FEATURE_FAILURE_LAYERSCOPE"_ns); return; } @@ -2638,11 +2638,9 @@ void gfxPlatform::InitCompositorAccelerationPrefs() { "Acceleration blocked by platform")) { if (StaticPrefs:: layers_acceleration_disabled_AtStartup_DoNotUseDirectly()) { - feature.UserDisable("Disabled by pref", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_PREF")); + feature.UserDisable("Disabled by pref", "FEATURE_FAILURE_COMP_PREF"_ns); } else if (acceleratedEnv && *acceleratedEnv == '0') { - feature.UserDisable("Disabled by envvar", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_ENV")); + feature.UserDisable("Disabled by envvar", "FEATURE_FAILURE_COMP_ENV"_ns); } } else { if (acceleratedEnv && *acceleratedEnv == '1') { @@ -2660,12 +2658,12 @@ void gfxPlatform::InitCompositorAccelerationPrefs() { if (InSafeMode()) { feature.ForceDisable(FeatureStatus::Blocked, "Acceleration blocked by safe-mode", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_SAFEMODE")); + "FEATURE_FAILURE_COMP_SAFEMODE"_ns); } if (IsHeadless()) { - feature.ForceDisable( - FeatureStatus::Blocked, "Acceleration blocked by headless mode", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_HEADLESSMODE")); + feature.ForceDisable(FeatureStatus::Blocked, + "Acceleration blocked by headless mode", + "FEATURE_FAILURE_COMP_HEADLESSMODE"_ns); } } @@ -2817,7 +2815,7 @@ void gfxPlatform::InitWebGPUConfig() { #ifndef NIGHTLY_BUILD feature.ForceDisable(FeatureStatus::Blocked, "WebGPU can only be enabled in nightly", - NS_LITERAL_CSTRING("WEBGPU_DISABLE_NON_NIGHTLY")); + "WEBGPU_DISABLE_NON_NIGHTLY"_ns); #endif } @@ -2847,30 +2845,30 @@ void gfxPlatform::InitOMTPConfig() { if (cpuCores <= 2) { omtp.ForceDisable(FeatureStatus::Broken, "OMTP is not supported on 32-bit with <= 2 cores", - NS_LITERAL_CSTRING("FEATURE_FAILURE_OMTP_32BIT_CORES")); + "FEATURE_FAILURE_OMTP_32BIT_CORES"_ns); } else if (mTotalSystemMemory < kMinSystemMemory) { omtp.ForceDisable(FeatureStatus::Broken, "OMTP is not supported on 32-bit with < 2 GB RAM", - NS_LITERAL_CSTRING("FEATURE_FAILURE_OMTP_32BIT_MEM")); + "FEATURE_FAILURE_OMTP_32BIT_MEM"_ns); } } if (mContentBackend == BackendType::CAIRO) { omtp.ForceDisable(FeatureStatus::Broken, "OMTP is not supported when using cairo", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_PREF")); + "FEATURE_FAILURE_COMP_PREF"_ns); } #ifdef XP_MACOSX if (!nsCocoaFeatures::OnYosemiteOrLater()) { omtp.ForceDisable(FeatureStatus::Blocked, "OMTP blocked before OSX 10.10", - NS_LITERAL_CSTRING("FEATURE_FAILURE_OMTP_OSX_MAVERICKS")); + "FEATURE_FAILURE_OMTP_OSX_MAVERICKS"_ns); } #endif if (InSafeMode()) { omtp.ForceDisable(FeatureStatus::Blocked, "OMTP blocked by safe-mode", - NS_LITERAL_CSTRING("FEATURE_FAILURE_COMP_SAFEMODE")); + "FEATURE_FAILURE_COMP_SAFEMODE"_ns); } if (omtp.IsEnabled()) { @@ -3292,9 +3290,8 @@ void gfxPlatform::NotifyCompositorCreated(LayersBackend aBackend) { void gfxPlatform::NotifyGPUProcessDisabled() { if (gfxConfig::IsEnabled(Feature::WEBRENDER)) { gfxConfig::GetFeature(Feature::WEBRENDER) - .ForceDisable( - FeatureStatus::Unavailable, "GPU Process is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_GPU_PROCESS_DISABLED")); + .ForceDisable(FeatureStatus::Unavailable, "GPU Process is disabled", + "FEATURE_FAILURE_GPU_PROCESS_DISABLED"_ns); gfxVars::SetUseWebRender(false); } gfxVars::SetRemoteCanvasEnabled(false); @@ -3379,9 +3376,9 @@ void gfxPlatform::InitOpenGLConfig() { // Check to see hw comp supported if (!gfxConfig::IsEnabled(Feature::HW_COMPOSITING)) { - openGLFeature.DisableByDefault( - FeatureStatus::Unavailable, "Hardware compositing is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_OPENGL_NEED_HWCOMP")); + openGLFeature.DisableByDefault(FeatureStatus::Unavailable, + "Hardware compositing is disabled", + "FEATURE_FAILURE_OPENGL_NEED_HWCOMP"_ns); return; } diff --git a/gfx/thebes/gfxPlatformFontList.cpp b/gfx/thebes/gfxPlatformFontList.cpp index c8489f80e5b2..26ccd34a01b8 100644 --- a/gfx/thebes/gfxPlatformFontList.cpp +++ b/gfx/thebes/gfxPlatformFontList.cpp @@ -473,7 +473,7 @@ nsresult gfxPlatformFontList::InitFontList() { } i.Data()->mShmemCharacterMap = nullptr; i.Data()->mShmemFace = nullptr; - i.Data()->mFamilyName = NS_LITERAL_CSTRING(""); + i.Data()->mFamilyName = ""_ns; } mFontEntries.Clear(); mShmemCharMaps.Clear(); @@ -1778,18 +1778,18 @@ void gfxPlatformFontList::AppendCJKPrefLangs(eFontPrefLang aPrefLangs[], // Then add the known CJK prefs in order of system preferred locales AutoTArray prefLocales; - prefLocales.AppendElement(NS_LITERAL_CSTRING("ja")); - prefLocales.AppendElement(NS_LITERAL_CSTRING("zh-CN")); - prefLocales.AppendElement(NS_LITERAL_CSTRING("zh-TW")); - prefLocales.AppendElement(NS_LITERAL_CSTRING("zh-HK")); - prefLocales.AppendElement(NS_LITERAL_CSTRING("ko")); + prefLocales.AppendElement("ja"_ns); + prefLocales.AppendElement("zh-CN"_ns); + prefLocales.AppendElement("zh-TW"_ns); + prefLocales.AppendElement("zh-HK"_ns); + prefLocales.AppendElement("ko"_ns); AutoTArray sysLocales; AutoTArray negLocales; if (NS_SUCCEEDED( OSPreferences::GetInstance()->GetSystemLocales(sysLocales))) { LocaleService::GetInstance()->NegotiateLanguages( - sysLocales, prefLocales, NS_LITERAL_CSTRING(""), + sysLocales, prefLocales, ""_ns, LocaleService::kLangNegStrategyFiltering, negLocales); for (const auto& localeStr : negLocales) { Locale locale(localeStr); diff --git a/gfx/thebes/gfxPlatformGtk.cpp b/gfx/thebes/gfxPlatformGtk.cpp index d7d544d422ff..221e8c68d5c8 100644 --- a/gfx/thebes/gfxPlatformGtk.cpp +++ b/gfx/thebes/gfxPlatformGtk.cpp @@ -131,7 +131,7 @@ void gfxPlatformGtk::InitPlatformGPUProcessPrefs() { FeatureState& gpuProc = gfxConfig::GetFeature(Feature::GPU_PROCESS); gpuProc.ForceDisable(FeatureStatus::Blocked, "Wayland does not work in the GPU process", - NS_LITERAL_CSTRING("FEATURE_FAILURE_WAYLAND")); + "FEATURE_FAILURE_WAYLAND"_ns); } #endif } diff --git a/gfx/thebes/gfxPlatformMac.cpp b/gfx/thebes/gfxPlatformMac.cpp index 1dbfed361122..00f002055e59 100644 --- a/gfx/thebes/gfxPlatformMac.cpp +++ b/gfx/thebes/gfxPlatformMac.cpp @@ -607,5 +607,5 @@ void gfxPlatformMac::InitPlatformGPUProcessPrefs() { FeatureState& gpuProc = gfxConfig::GetFeature(Feature::GPU_PROCESS); gpuProc.ForceDisable(FeatureStatus::Blocked, "GPU process does not work on Mac", - NS_LITERAL_CSTRING("FEATURE_FAILURE_MAC_GPU_PROC")); + "FEATURE_FAILURE_MAC_GPU_PROC"_ns); } diff --git a/gfx/thebes/gfxSVGGlyphs.cpp b/gfx/thebes/gfxSVGGlyphs.cpp index 19684e74589e..daed1291d258 100644 --- a/gfx/thebes/gfxSVGGlyphs.cpp +++ b/gfx/thebes/gfxSVGGlyphs.cpp @@ -34,8 +34,8 @@ #include "harfbuzz/hb.h" #include "zlib.h" -#define SVG_CONTENT_TYPE NS_LITERAL_CSTRING("image/svg+xml") -#define UTF8_CHARSET NS_LITERAL_CSTRING("utf-8") +#define SVG_CONTENT_TYPE "image/svg+xml"_ns +#define UTF8_CHARSET "utf-8"_ns using namespace mozilla; using mozilla::dom::Document; @@ -431,7 +431,7 @@ void gfxSVGGlyphsDocument::InsertGlyphId(Element* aGlyphElement) { // The maximum glyph ID is 65535 so the maximum length of the numeric part // is 5. if (!aGlyphElement->GetAttr(kNameSpaceID_None, nsGkAtoms::id, glyphIdStr) || - !StringBeginsWith(glyphIdStr, NS_LITERAL_STRING("glyph")) || + !StringBeginsWith(glyphIdStr, u"glyph"_ns) || glyphIdStr.Length() > glyphPrefixLength + 5) { return; } diff --git a/gfx/thebes/gfxUserFontSet.cpp b/gfx/thebes/gfxUserFontSet.cpp index 3f13ca9885d6..1c93c5c7b439 100644 --- a/gfx/thebes/gfxUserFontSet.cpp +++ b/gfx/thebes/gfxUserFontSet.cpp @@ -40,7 +40,7 @@ gfxUserFontEntry::gfxUserFontEntry( const nsTArray& aVariationSettings, uint32_t aLanguageOverride, gfxCharacterMap* aUnicodeRanges, StyleFontDisplay aFontDisplay, RangeFlags aRangeFlags) - : gfxFontEntry(NS_LITERAL_CSTRING("userfont")), + : gfxFontEntry("userfont"_ns), mUserFontLoadState(STATUS_NOT_LOADED), mFontDataLoadingState(NOT_LOADING), mUnsupportedFormat(false), @@ -1277,7 +1277,7 @@ void gfxUserFontSet::UserFontCache::Entry::ReportMemory( EmptyCString(), path, nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, mFontEntry->ComputedSizeOfExcludingThis(UserFontsMallocSizeOf), - NS_LITERAL_CSTRING("Memory used by @font-face resource."), aData); + "Memory used by @font-face resource."_ns, aData); } NS_IMPL_ISUPPORTS(gfxUserFontSet::UserFontCache::MemoryReporter, diff --git a/gfx/thebes/gfxUtils.cpp b/gfx/thebes/gfxUtils.cpp index b2fd154be70c..5b269ca71244 100644 --- a/gfx/thebes/gfxUtils.cpp +++ b/gfx/thebes/gfxUtils.cpp @@ -1367,8 +1367,7 @@ class GetFeatureStatusWorkerRunnable final const nsCOMPtr& gfxInfo, int32_t feature, nsACString& failureId, int32_t* status) - : WorkerMainThreadRunnable(workerPrivate, - NS_LITERAL_CSTRING("GFX :: GetFeatureStatus")), + : WorkerMainThreadRunnable(workerPrivate, "GFX :: GetFeatureStatus"_ns), mGfxInfo(gfxInfo), mFeature(feature), mStatus(status), diff --git a/gfx/thebes/gfxWindowsPlatform.cpp b/gfx/thebes/gfxWindowsPlatform.cpp index ab19bf1e9a41..6e0fb7447a67 100644 --- a/gfx/thebes/gfxWindowsPlatform.cpp +++ b/gfx/thebes/gfxWindowsPlatform.cpp @@ -570,7 +570,7 @@ gfxPlatformFontList* gfxWindowsPlatform::CreatePlatformFontList() { // So we're going to fall back to GDI fonts & rendering. gfxPlatformFontList::Shutdown(); DisableD2D(FeatureStatus::Failed, "Failed to initialize fonts", - NS_LITERAL_CSTRING("FEATURE_FAILURE_FONT_FAIL")); + "FEATURE_FAILURE_FONT_FAIL"_ns); } // Ensure this is false, even if the Windows version was recent enough to @@ -1257,9 +1257,9 @@ static void InitializeANGLEConfig() { FeatureState& d3d11ANGLE = gfxConfig::GetFeature(Feature::D3D11_HW_ANGLE); if (!gfxConfig::IsEnabled(Feature::D3D11_COMPOSITING)) { - d3d11ANGLE.DisableByDefault( - FeatureStatus::Unavailable, "D3D11 compositing is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_DISABLED")); + d3d11ANGLE.DisableByDefault(FeatureStatus::Unavailable, + "D3D11 compositing is disabled", + "FEATURE_FAILURE_D3D11_DISABLED"_ns); return; } @@ -1299,9 +1299,9 @@ void gfxWindowsPlatform::InitializeD3D11Config() { FeatureState& d3d11 = gfxConfig::GetFeature(Feature::D3D11_COMPOSITING); if (!gfxConfig::IsEnabled(Feature::HW_COMPOSITING)) { - d3d11.DisableByDefault( - FeatureStatus::Unavailable, "Hardware compositing is disabled", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D3D11_NEED_HWCOMP")); + d3d11.DisableByDefault(FeatureStatus::Unavailable, + "Hardware compositing is disabled", + "FEATURE_FAILURE_D3D11_NEED_HWCOMP"_ns); return; } @@ -1326,7 +1326,7 @@ void gfxWindowsPlatform::InitializeD3D11Config() { adaptorId.EqualsLiteral("0x1902")) { #ifdef RELEASE_OR_BETA d3d11.Disable(FeatureStatus::Blocklisted, "Blocklisted, see bug 1351349", - NS_LITERAL_CSTRING("FEATURE_FAILURE_BUG_1351349")); + "FEATURE_FAILURE_BUG_1351349"_ns); #else Preferences::SetBool("gfx.compositor.clearstate", true); #endif @@ -1362,7 +1362,7 @@ void gfxWindowsPlatform::InitializeAdvancedLayersConfig() { } else { al.Disable(FeatureStatus::Disabled, "Advanced Layers is disabled on Windows 7 by default", - NS_LITERAL_CSTRING("FEATURE_FAILURE_DISABLED_ON_WIN7")); + "FEATURE_FAILURE_DISABLED_ON_WIN7"_ns); } } @@ -1373,10 +1373,10 @@ void gfxWindowsPlatform::InitializeAdvancedLayersConfig() { } else if (gfxVars::UseWebRender()) { al.Disable(FeatureStatus::Blocked, "Blocked from fallback candidate by WebRender usage", - NS_LITERAL_CSTRING("FEATURE_BLOCKED_BY_WEBRENDER_USAGE")); + "FEATURE_BLOCKED_BY_WEBRENDER_USAGE"_ns); } else if (Preferences::GetBool("layers.mlgpu.sanity-test-failed", false)) { al.Disable(FeatureStatus::Broken, "Failed to render sanity test", - NS_LITERAL_CSTRING("FEATURE_FAILURE_FAILED_TO_RENDER")); + "FEATURE_FAILURE_FAILED_TO_RENDER"_ns); } } @@ -1509,7 +1509,7 @@ void gfxWindowsPlatform::InitializeD2DConfig() { if (!gfxConfig::IsEnabled(Feature::D3D11_COMPOSITING)) { d2d1.DisableByDefault(FeatureStatus::Unavailable, "Direct2D requires Direct3D 11 compositing", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_D3D11_COMP")); + "FEATURE_FAILURE_D2D_D3D11_COMP"_ns); return; } @@ -1542,7 +1542,7 @@ void gfxWindowsPlatform::InitializeD2D() { if (dm->IsWARP()) { d2d1.Disable(FeatureStatus::Blocked, "Direct2D is not compatible with Direct3D11 WARP", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_WARP_BLOCK")); + "FEATURE_FAILURE_D2D_WARP_BLOCK"_ns); } // If we pass all the initial checks, we can proceed to runtime decisions. @@ -1553,21 +1553,21 @@ void gfxWindowsPlatform::InitializeD2D() { if (!Factory::SupportsD2D1()) { d2d1.SetFailed(FeatureStatus::Unavailable, "Failed to acquire a Direct2D 1.1 factory", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_FACTORY")); + "FEATURE_FAILURE_D2D_FACTORY"_ns); return; } if (!dm->GetContentDevice()) { d2d1.SetFailed(FeatureStatus::Failed, "Failed to acquire a Direct3D 11 content device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_DEVICE")); + "FEATURE_FAILURE_D2D_DEVICE"_ns); return; } if (!dm->TextureSharingWorks()) { d2d1.SetFailed(FeatureStatus::Failed, "Direct3D11 device does not support texture sharing", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_TXT_SHARING")); + "FEATURE_FAILURE_D2D_TXT_SHARING"_ns); return; } @@ -1575,7 +1575,7 @@ void gfxWindowsPlatform::InitializeD2D() { if (!DWriteEnabled() && !InitDWriteSupport()) { d2d1.SetFailed(FeatureStatus::Failed, "Failed to initialize DirectWrite support", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_DWRITE")); + "FEATURE_FAILURE_D2D_DWRITE"_ns); return; } @@ -1583,7 +1583,7 @@ void gfxWindowsPlatform::InitializeD2D() { RefPtr contentDevice = dm->GetContentDevice(); if (!Factory::SetDirect3D11Device(contentDevice)) { d2d1.SetFailed(FeatureStatus::Failed, "Failed to create a Direct2D device", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_CREATE_FAILED")); + "FEATURE_FAILURE_D2D_CREATE_FAILED"_ns); return; } @@ -1614,21 +1614,21 @@ bool gfxWindowsPlatform::InitGPUProcessSupport() { } gpuProc.Disable(FeatureStatus::Unavailable, "Not using GPU Process since D3D11 is unavailable", - NS_LITERAL_CSTRING("FEATURE_FAILURE_NO_D3D11")); + "FEATURE_FAILURE_NO_D3D11"_ns); } else if (!IsWin7SP1OrLater()) { // On Windows 7 Pre-SP1, DXGI 1.2 is not available and remote presentation // for D3D11 will not work. Rather than take a regression we revert back // to in-process rendering. gpuProc.Disable(FeatureStatus::Unavailable, "Windows 7 Pre-SP1 cannot use the GPU process", - NS_LITERAL_CSTRING("FEATURE_FAILURE_OLD_WINDOWS")); + "FEATURE_FAILURE_OLD_WINDOWS"_ns); } else if (!IsWin8OrLater()) { // Windows 7 SP1 can have DXGI 1.2 only via the Platform Update, so we // explicitly check for that here. if (!DeviceManagerDx::Get()->CheckRemotePresentSupport()) { gpuProc.Disable(FeatureStatus::Unavailable, "GPU Process requires the Windows 7 Platform Update", - NS_LITERAL_CSTRING("FEATURE_FAILURE_PLATFORM_UPDATE")); + "FEATURE_FAILURE_PLATFORM_UPDATE"_ns); } else { // Clear anything cached by the above call since we don't need it. DeviceManagerDx::Get()->ResetDevices(); @@ -1985,7 +1985,7 @@ void gfxWindowsPlatform::ImportGPUDeviceData( if (d2d1.IsEnabled()) { d2d1.SetFailed(FeatureStatus::Unavailable, "Direct2D requires Direct3D 11 compositing", - NS_LITERAL_CSTRING("FEATURE_FAILURE_D2D_D3D11_COMP")); + "FEATURE_FAILURE_D2D_D3D11_COMP"_ns); } } diff --git a/gfx/vr/VRManager.cpp b/gfx/vr/VRManager.cpp index 210b6f508de6..7cc3184f34b8 100644 --- a/gfx/vr/VRManager.cpp +++ b/gfx/vr/VRManager.cpp @@ -1355,7 +1355,7 @@ void VRManager::SubmitFrame(VRLayerParent* aLayer, mCurrentSubmitTask = task; #if !defined(MOZ_WIDGET_ANDROID) if (!mSubmitThread) { - mSubmitThread = new VRThread(NS_LITERAL_CSTRING("VR_SubmitFrame")); + mSubmitThread = new VRThread("VR_SubmitFrame"_ns); } mSubmitThread->Start(); mSubmitThread->PostTask(task.forget()); diff --git a/gfx/vr/ipc/VRProcessManager.cpp b/gfx/vr/ipc/VRProcessManager.cpp index 9bcdb61aa9e1..d8732e827297 100644 --- a/gfx/vr/ipc/VRProcessManager.cpp +++ b/gfx/vr/ipc/VRProcessManager.cpp @@ -86,7 +86,7 @@ void VRProcessManager::DestroyProcess() { mVRChild = nullptr; CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::VRProcessStatus, - NS_LITERAL_CSTRING("Destroyed")); + "Destroyed"_ns); } bool VRProcessManager::EnsureVRReady() { @@ -133,7 +133,7 @@ void VRProcessManager::OnProcessLaunchComplete(VRProcessParent* aParent) { mQueuedPrefs.Clear(); CrashReporter::AnnotateCrashReport(CrashReporter::Annotation::VRProcessStatus, - NS_LITERAL_CSTRING("Running")); + "Running"_ns); } void VRProcessManager::OnProcessUnexpectedShutdown(VRProcessParent* aParent) { diff --git a/gfx/vr/nsFxrCommandLineHandler.cpp b/gfx/vr/nsFxrCommandLineHandler.cpp index 450e88f81bbc..7dca745fcfb5 100644 --- a/gfx/vr/nsFxrCommandLineHandler.cpp +++ b/gfx/vr/nsFxrCommandLineHandler.cpp @@ -63,8 +63,7 @@ NS_IMPL_ISUPPORTS(nsFxrCommandLineHandler, nsICommandLineHandler) NS_IMETHODIMP nsFxrCommandLineHandler::Handle(nsICommandLine* aCmdLine) { bool handleFlagRetVal = false; - nsresult result = - aCmdLine->HandleFlag(NS_LITERAL_STRING("fxr"), false, &handleFlagRetVal); + nsresult result = aCmdLine->HandleFlag(u"fxr"_ns, false, &handleFlagRetVal); if (result == NS_OK && handleFlagRetVal) { if (XRE_IsParentProcess() && !XRE_IsE10sParentProcess()) { MOZ_CRASH("--fxr not supported without e10s"); diff --git a/gfx/vr/service/OculusSession.cpp b/gfx/vr/service/OculusSession.cpp index 64e9f55168dd..ac6bba3e9734 100644 --- a/gfx/vr/service/OculusSession.cpp +++ b/gfx/vr/service/OculusSession.cpp @@ -589,7 +589,7 @@ bool OculusSession::LoadOvrLib() { if (libPath.Length() == 0) { fullName.Assign(libName); } else { - fullName.Assign(libPath + NS_LITERAL_STRING(u"\\") + libName); + fullName.Assign(libPath + u"\\"_ns + libName); } mOvrLib = LoadLibraryWithFlags(fullName.get()); diff --git a/gfx/vr/service/OpenVRSession.cpp b/gfx/vr/service/OpenVRSession.cpp index 951a455557d1..639f0f73d3a5 100644 --- a/gfx/vr/service/OpenVRSession.cpp +++ b/gfx/vr/service/OpenVRSession.cpp @@ -1369,7 +1369,7 @@ void OpenVRSession::VibrateHaptic(uint32_t aControllerIdx, void OpenVRSession::StartHapticThread() { MOZ_ASSERT(NS_IsMainThread()); if (!mHapticThread) { - mHapticThread = new VRThread(NS_LITERAL_CSTRING("VR_OpenVR_Haptics")); + mHapticThread = new VRThread("VR_OpenVR_Haptics"_ns); } mHapticThread->Start(); StartHapticTimer(); diff --git a/hal/HalWakeLock.cpp b/hal/HalWakeLock.cpp index 96c1cf364058..b36ba3828098 100644 --- a/hal/HalWakeLock.cpp +++ b/hal/HalWakeLock.cpp @@ -104,8 +104,7 @@ CleanupOnContentShutdown::Observe(nsISupports* aSubject, const char* aTopic, } uint64_t childID = 0; - nsresult rv = - props->GetPropertyAsUint64(NS_LITERAL_STRING("childID"), &childID); + nsresult rv = props->GetPropertyAsUint64(u"childID"_ns, &childID); if (NS_SUCCEEDED(rv)) { for (auto iter = sLockTable->Iter(); !iter.Done(); iter.Next()) { auto table = iter.UserData(); diff --git a/image/DecodePool.cpp b/image/DecodePool.cpp index e31aeb16dd11..af01b9dfd738 100644 --- a/image/DecodePool.cpp +++ b/image/DecodePool.cpp @@ -318,7 +318,7 @@ bool DecodePoolImpl::CreateThread() { MOZ_ASSERT_UNREACHABLE("Should successfully create image decoding threads"); return false; } - thread->SetNameForWakeupTelemetry(NS_LITERAL_CSTRING("ImgDecoder (all)")); + thread->SetNameForWakeupTelemetry("ImgDecoder (all)"_ns); mThreads.AppendElement(std::move(thread)); --mAvailableThreads; diff --git a/image/RasterImage.cpp b/image/RasterImage.cpp index 8883b36a66d1..d2fff56600d5 100644 --- a/image/RasterImage.cpp +++ b/image/RasterImage.cpp @@ -1807,12 +1807,12 @@ void RasterImage::ReportDecoderError() { do_CreateInstance(NS_SCRIPTERROR_CONTRACTID); if (consoleService && errorObject) { - nsAutoString msg(NS_LITERAL_STRING("Image corrupt or truncated.")); + nsAutoString msg(u"Image corrupt or truncated."_ns); nsAutoString src; if (GetURI()) { nsAutoCString uri; if (!GetSpecTruncatedTo1k(uri)) { - msg += NS_LITERAL_STRING(" URI in this note truncated due to length."); + msg += u" URI in this note truncated due to length."_ns; } src = NS_ConvertUTF8toUTF16(uri); } diff --git a/image/SVGDocumentWrapper.cpp b/image/SVGDocumentWrapper.cpp index 9f018c376c75..77661c33cf39 100644 --- a/image/SVGDocumentWrapper.cpp +++ b/image/SVGDocumentWrapper.cpp @@ -290,9 +290,8 @@ nsresult SVGDocumentWrapper::SetupViewer(nsIRequest* aRequest, nsCOMPtr viewer; nsCOMPtr listener; rv = docLoaderFactory->CreateInstance( - "external-resource", chan, newLoadGroup, - NS_LITERAL_CSTRING(IMAGE_SVG_XML), nullptr, nullptr, - getter_AddRefs(listener), getter_AddRefs(viewer)); + "external-resource", chan, newLoadGroup, nsLiteralCString(IMAGE_SVG_XML), + nullptr, nullptr, getter_AddRefs(listener), getter_AddRefs(viewer)); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED); diff --git a/image/VectorImage.cpp b/image/VectorImage.cpp index 49abfc946791..0836a9cbb579 100644 --- a/image/VectorImage.cpp +++ b/image/VectorImage.cpp @@ -175,12 +175,10 @@ class SVGLoadEventListener final : public nsIDOMEventListener { MOZ_ASSERT(mDocument, "Need an SVG document"); MOZ_ASSERT(mImage, "Need an image"); - mDocument->AddEventListener(NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), - this, true, false); - mDocument->AddEventListener(NS_LITERAL_STRING("SVGAbort"), this, true, - false); - mDocument->AddEventListener(NS_LITERAL_STRING("SVGError"), this, true, + mDocument->AddEventListener(u"MozSVGAsImageDocumentLoad"_ns, this, true, false); + mDocument->AddEventListener(u"SVGAbort"_ns, this, true, false); + mDocument->AddEventListener(u"SVGError"_ns, this, true, false); } private: @@ -220,10 +218,10 @@ class SVGLoadEventListener final : public nsIDOMEventListener { void Cancel() { MOZ_ASSERT(mDocument, "Duplicate call to Cancel"); if (mDocument) { - mDocument->RemoveEventListener( - NS_LITERAL_STRING("MozSVGAsImageDocumentLoad"), this, true); - mDocument->RemoveEventListener(NS_LITERAL_STRING("SVGAbort"), this, true); - mDocument->RemoveEventListener(NS_LITERAL_STRING("SVGError"), this, true); + mDocument->RemoveEventListener(u"MozSVGAsImageDocumentLoad"_ns, this, + true); + mDocument->RemoveEventListener(u"SVGAbort"_ns, this, true); + mDocument->RemoveEventListener(u"SVGError"_ns, this, true); mDocument = nullptr; } } diff --git a/image/build/nsImageModule.cpp b/image/build/nsImageModule.cpp index 5974115877c8..055b07558555 100644 --- a/image/build/nsImageModule.cpp +++ b/image/build/nsImageModule.cpp @@ -32,10 +32,9 @@ static void UpdateContentViewerRegistration(const char* aPref, void* aData) { return; } - static nsLiteralCString kCategory = - NS_LITERAL_CSTRING("Gecko-Content-Viewers"); - static nsLiteralCString kContractId = NS_LITERAL_CSTRING( - "@mozilla.org/content/plugin/document-loader-factory;1"); + static nsLiteralCString kCategory = "Gecko-Content-Viewers"_ns; + static nsLiteralCString kContractId = + "@mozilla.org/content/plugin/document-loader-factory;1"_ns; if (cookie->mIsEnabled()) { catMan->AddCategoryEntry(kCategory, cookie->mMimeType, kContractId, @@ -56,11 +55,9 @@ nsresult mozilla::image::EnsureModuleInitialized() { } static ImageEnablementCookie kAVIFCookie = { - mozilla::StaticPrefs::image_avif_enabled, - NS_LITERAL_CSTRING("image/avif")}; + mozilla::StaticPrefs::image_avif_enabled, "image/avif"_ns}; static ImageEnablementCookie kWebPCookie = { - mozilla::StaticPrefs::image_webp_enabled, - NS_LITERAL_CSTRING("image/webp")}; + mozilla::StaticPrefs::image_webp_enabled, "image/webp"_ns}; Preferences::RegisterCallbackAndCall(UpdateContentViewerRegistration, "image.avif.enabled", &kAVIFCookie); Preferences::RegisterCallbackAndCall(UpdateContentViewerRegistration, diff --git a/image/decoders/icon/android/nsIconChannel.cpp b/image/decoders/icon/android/nsIconChannel.cpp index 83897456bcfe..7599cf2bb70e 100644 --- a/image/decoders/icon/android/nsIconChannel.cpp +++ b/image/decoders/icon/android/nsIconChannel.cpp @@ -104,7 +104,7 @@ static nsresult moz_icon_to_channel(nsIURI* aURI, const nsACString& aFileExt, return NS_NewInputStreamChannel( aChannel, aURI, stream.forget(), nullPrincipal, nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED, - nsIContentPolicy::TYPE_INTERNAL_IMAGE, NS_LITERAL_CSTRING(IMAGE_ICON_MS)); + nsIContentPolicy::TYPE_INTERNAL_IMAGE, nsLiteralCString(IMAGE_ICON_MS)); } nsresult nsIconChannel::Init(nsIURI* aURI) { diff --git a/image/decoders/icon/gtk/nsIconChannel.cpp b/image/decoders/icon/gtk/nsIconChannel.cpp index ac95a6487f42..954bd7beb19b 100644 --- a/image/decoders/icon/gtk/nsIconChannel.cpp +++ b/image/decoders/icon/gtk/nsIconChannel.cpp @@ -99,7 +99,7 @@ static nsresult moz_gdk_pixbuf_to_channel(GdkPixbuf* aPixbuf, nsIURI* aURI, return NS_NewInputStreamChannel( aChannel, aURI, stream.forget(), nullPrincipal, nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED, - nsIContentPolicy::TYPE_INTERNAL_IMAGE, NS_LITERAL_CSTRING(IMAGE_ICON_MS)); + nsIContentPolicy::TYPE_INTERNAL_IMAGE, nsLiteralCString(IMAGE_ICON_MS)); } static GtkWidget* gProtoWindow = nullptr; @@ -298,9 +298,9 @@ nsresult nsIconChannel::Init(nsIURI* aURI) { // First lookup the icon by stock id and text direction. GtkTextDirection direction = GTK_TEXT_DIR_NONE; - if (StringEndsWith(stockIcon, NS_LITERAL_CSTRING("-ltr"))) { + if (StringEndsWith(stockIcon, "-ltr"_ns)) { direction = GTK_TEXT_DIR_LTR; - } else if (StringEndsWith(stockIcon, NS_LITERAL_CSTRING("-rtl"))) { + } else if (StringEndsWith(stockIcon, "-rtl"_ns)) { direction = GTK_TEXT_DIR_RTL; } diff --git a/image/decoders/icon/nsIconURI.cpp b/image/decoders/icon/nsIconURI.cpp index fc064be51b55..f98db9d8ff19 100644 --- a/image/decoders/icon/nsIconURI.cpp +++ b/image/decoders/icon/nsIconURI.cpp @@ -267,7 +267,7 @@ nsresult nsMozIconURI::SetSpecInternal(const nsACString& aSpec) { return NS_OK; } - if (StringBeginsWith(iconPath, NS_LITERAL_CSTRING("//"))) { + if (StringBeginsWith(iconPath, "//"_ns)) { // Sanity check this supposed dummy file name. if (iconPath.Length() > SANE_FILE_NAME_LEN) { return NS_ERROR_MALFORMED_URI; diff --git a/image/decoders/icon/win/nsIconChannel.cpp b/image/decoders/icon/win/nsIconChannel.cpp index 28816570b597..16657ca35e1f 100644 --- a/image/decoders/icon/win/nsIconChannel.cpp +++ b/image/decoders/icon/win/nsIconChannel.cpp @@ -498,7 +498,7 @@ nsresult nsIconChannel::GetHIconFromFile(bool aNonBlocking, HICON* hIcon) { // If the mime service does not know about this mime type, we show // the generic icon. // In any case, we need to insert a '.' before the extension. - filePath = NS_LITERAL_STRING(".") + NS_ConvertUTF8toUTF16(defFileExt); + filePath = u"."_ns + NS_ConvertUTF8toUTF16(defFileExt); } if (aNonBlocking) { diff --git a/image/encoders/jpeg/nsJPEGEncoder.cpp b/image/encoders/jpeg/nsJPEGEncoder.cpp index 0b46791eab64..d4e7eced387d 100644 --- a/image/encoders/jpeg/nsJPEGEncoder.cpp +++ b/image/encoders/jpeg/nsJPEGEncoder.cpp @@ -123,7 +123,7 @@ nsJPEGEncoder::InitFromData(const uint8_t* aData, int quality = 92; if (aOutputOptions.Length() > 0) { // have options string - const nsString qualityPrefix(NS_LITERAL_STRING("quality=")); + const nsString qualityPrefix(u"quality="_ns); if (aOutputOptions.Length() > qualityPrefix.Length() && StringBeginsWith(aOutputOptions, qualityPrefix)) { // have quality string diff --git a/image/imgLoader.cpp b/image/imgLoader.cpp index b80ab8e0fad3..bf41b740726e 100644 --- a/image/imgLoader.cpp +++ b/image/imgLoader.cpp @@ -286,7 +286,7 @@ class imgMemoryReporter final : public nsIMemoryReporter { nsISupports* aData, const char* aPathPrefix, const ImageMemoryCounter& aCounter, layers::SharedSurfacesMemoryReport& aSharedSurfaces) { - nsAutoCString pathPrefix(NS_LITERAL_CSTRING("explicit/")); + nsAutoCString pathPrefix("explicit/"_ns); pathPrefix.Append(aPathPrefix); switch (aCounter.Type()) { @@ -2799,7 +2799,7 @@ ProxyListener::OnStartRequest(nsIRequest* aRequest) { nsAutoString type; timedChannel->GetInitiatorType(type); if (type.IsEmpty()) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("img")); + timedChannel->SetInitiatorType(u"img"_ns); } } @@ -2811,7 +2811,7 @@ ProxyListener::OnStartRequest(nsIRequest* aRequest) { in the pipeline to handle the content and pass it along to our original listener. */ - if (NS_LITERAL_CSTRING("multipart/x-mixed-replace").Equals(contentType)) { + if ("multipart/x-mixed-replace"_ns.Equals(contentType)) { nsCOMPtr convServ( do_GetService("@mozilla.org/streamConverters;1", &rv)); if (NS_SUCCEEDED(rv)) { diff --git a/image/imgTools.cpp b/image/imgTools.cpp index 6cbe0ae3585a..7339eac766b9 100644 --- a/image/imgTools.cpp +++ b/image/imgTools.cpp @@ -430,8 +430,7 @@ static nsresult EncodeImageData(DataSourceSurface* aDataSurface, "We're assuming B8G8R8A8/X8"); // Get an image encoder for the media type - nsAutoCString encoderCID( - NS_LITERAL_CSTRING("@mozilla.org/image/encoder;2?type=") + aMimeType); + nsAutoCString encoderCID("@mozilla.org/image/encoder;2?type="_ns + aMimeType); nsCOMPtr encoder = do_CreateInstance(encoderCID.get()); if (!encoder) { diff --git a/intl/hyphenation/glue/nsHyphenationManager.cpp b/intl/hyphenation/glue/nsHyphenationManager.cpp index 8e7b8d897bee..b2058ac6eadc 100644 --- a/intl/hyphenation/glue/nsHyphenationManager.cpp +++ b/intl/hyphenation/glue/nsHyphenationManager.cpp @@ -132,7 +132,7 @@ already_AddRefed nsHyphenationManager::GetHyphenator( // successive trailing subtags with "-*" to find fallback patterns, // so "de-DE-1996" -> "de-DE-*" (and then recursively -> "de-*") nsAtomCString localeStr(aLocale); - if (StringEndsWith(localeStr, NS_LITERAL_CSTRING("-*"))) { + if (StringEndsWith(localeStr, "-*"_ns)) { localeStr.Truncate(localeStr.Length() - 2); } int32_t i = localeStr.RFindChar('-'); @@ -178,7 +178,7 @@ void nsHyphenationManager::LoadPatternList() { nsCOMPtr greDir; rv = dirSvc->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir)); if (NS_SUCCEEDED(rv)) { - greDir->AppendNative(NS_LITERAL_CSTRING("hyphenation")); + greDir->AppendNative("hyphenation"_ns); LoadPatternListFromDir(greDir); } @@ -186,7 +186,7 @@ void nsHyphenationManager::LoadPatternList() { rv = dirSvc->Get(NS_XPCOM_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(appDir)); if (NS_SUCCEEDED(rv)) { - appDir->AppendNative(NS_LITERAL_CSTRING("hyphenation")); + appDir->AppendNative("hyphenation"_ns); bool equals; if (NS_SUCCEEDED(appDir->Equals(greDir, &equals)) && !equals) { LoadPatternListFromDir(appDir); @@ -197,7 +197,7 @@ void nsHyphenationManager::LoadPatternList() { rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR, getter_AddRefs(profileDir)); if (NS_SUCCEEDED(rv)) { - profileDir->AppendNative(NS_LITERAL_CSTRING("hyphenation")); + profileDir->AppendNative("hyphenation"_ns); LoadPatternListFromDir(profileDir); } } @@ -205,12 +205,12 @@ void nsHyphenationManager::LoadPatternList() { // Extract the locale code we'll use to identify a given hyphenation resource // from the path name as found in omnijar or on disk. static already_AddRefed LocaleAtomFromPath(const nsCString& aPath) { - MOZ_ASSERT(StringEndsWith(aPath, NS_LITERAL_CSTRING(".hyf"))); + MOZ_ASSERT(StringEndsWith(aPath, ".hyf"_ns)); nsCString locale(aPath); locale.Truncate(locale.Length() - 4); // strip ".hyf" locale.Cut(0, locale.RFindChar('/') + 1); // strip directory ToLowerCase(locale); - if (StringBeginsWith(locale, NS_LITERAL_CSTRING("hyph_"))) { + if (StringBeginsWith(locale, "hyph_"_ns)) { locale.Cut(0, 5); } for (uint32_t i = 0; i < locale.Length(); ++i) { @@ -286,7 +286,7 @@ void nsHyphenationManager::LoadPatternListFromDir(nsIFile* aDir) { nsAutoString dictName; file->GetLeafName(dictName); NS_ConvertUTF16toUTF8 path(dictName); - if (!StringEndsWith(path, NS_LITERAL_CSTRING(".hyf"))) { + if (!StringEndsWith(path, ".hyf"_ns)) { continue; } RefPtr localeAtom = LocaleAtomFromPath(path); diff --git a/intl/l10n/FluentResource.cpp b/intl/l10n/FluentResource.cpp index 94211a86b859..d40fb220cfb2 100644 --- a/intl/l10n/FluentResource.cpp +++ b/intl/l10n/FluentResource.cpp @@ -30,8 +30,8 @@ already_AddRefed FluentResource::Constructor( if (res->mHasErrors) { nsContentUtils::LogSimpleConsoleError( - NS_LITERAL_STRING("Errors encountered while parsing Fluent Resource."), - "chrome", false, true /* from chrome context*/); + u"Errors encountered while parsing Fluent Resource."_ns, "chrome", + false, true /* from chrome context*/); } return res.forget(); } diff --git a/intl/locale/LocaleService.cpp b/intl/locale/LocaleService.cpp index 765a44b2b18c..59a5fc64f4f3 100644 --- a/intl/locale/LocaleService.cpp +++ b/intl/locale/LocaleService.cpp @@ -486,7 +486,7 @@ LocaleService::GetRegionalPrefsLocales(nsTArray& aRetVal) { NS_IMETHODIMP LocaleService::GetWebExposedLocales(nsTArray& aRetVal) { if (StaticPrefs::privacy_spoof_english() == 2) { - aRetVal = nsTArray({NS_LITERAL_CSTRING("en-US")}); + aRetVal = nsTArray({"en-US"_ns}); return NS_OK; } diff --git a/intl/locale/OSPreferences.cpp b/intl/locale/OSPreferences.cpp index e4f289755afd..52f2a550f452 100644 --- a/intl/locale/OSPreferences.cpp +++ b/intl/locale/OSPreferences.cpp @@ -249,7 +249,7 @@ OSPreferences::GetSystemLocales(nsTArray& aRetVal) { // If we failed to get the system locale, we still need // to return something because there are tests out there that // depend on system locale to be set. - aRetVal.AppendElement(NS_LITERAL_CSTRING("en-US")); + aRetVal.AppendElement("en-US"_ns); return NS_ERROR_FAILURE; } diff --git a/intl/locale/nsLanguageAtomService.cpp b/intl/locale/nsLanguageAtomService.cpp index f24e980e24a0..bac4c7a1dca8 100644 --- a/intl/locale/nsLanguageAtomService.cpp +++ b/intl/locale/nsLanguageAtomService.cpp @@ -178,7 +178,7 @@ nsStaticAtom* nsLanguageAtomService::GetUncachedLanguageGroup( nsACString::const_iterator start, end; langStr.BeginReading(start); langStr.EndReading(end); - if (FindInReadable(NS_LITERAL_CSTRING("-x-"), start, end)) { + if (FindInReadable("-x-"_ns, start, end)) { // The substring we want ends at the beginning of the "-x-" subtag. langStr.Truncate(start.get() - langStr.BeginReading()); } diff --git a/intl/locale/tests/gtest/TestCollation.cpp b/intl/locale/tests/gtest/TestCollation.cpp index 90fd0ef2b8d1..95f7df5d4057 100644 --- a/intl/locale/tests/gtest/TestCollation.cpp +++ b/intl/locale/tests/gtest/TestCollation.cpp @@ -19,20 +19,20 @@ TEST(Collation, AllocateRowSortKey) // Don't throw error even if locale name is invalid nsCOMPtr collator; - nsresult rv = colFactory->CreateCollationForLocale( - NS_LITERAL_CSTRING("$languageName"), getter_AddRefs(collator)); + nsresult rv = colFactory->CreateCollationForLocale("$languageName"_ns, + getter_AddRefs(collator)); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsTArray sortKey1; // Don't throw error even if locale name is invalid rv = collator->AllocateRawSortKey(nsICollation::kCollationStrengthDefault, - NS_LITERAL_STRING("ABC"), sortKey1); + u"ABC"_ns, sortKey1); ASSERT_TRUE(NS_SUCCEEDED(rv)); nsTArray sortKey2; // Don't throw error even if locale name is invalid rv = collator->AllocateRawSortKey(nsICollation::kCollationStrengthDefault, - NS_LITERAL_STRING("DEF"), sortKey2); + u"DEF"_ns, sortKey2); ASSERT_TRUE(NS_SUCCEEDED(rv)); int32_t result; diff --git a/intl/locale/tests/gtest/TestLocaleService.cpp b/intl/locale/tests/gtest/TestLocaleService.cpp index c9cf1a762d77..09a88812e9f4 100644 --- a/intl/locale/tests/gtest/TestLocaleService.cpp +++ b/intl/locale/tests/gtest/TestLocaleService.cpp @@ -82,7 +82,7 @@ TEST(Intl_Locale_LocaleService, GetRegionalPrefsLocales) TEST(Intl_Locale_LocaleService, GetWebExposedLocales) { - const nsTArray spoofLocale{NS_LITERAL_CSTRING("de")}; + const nsTArray spoofLocale{"de"_ns}; LocaleService::GetInstance()->SetAvailableLocales(spoofLocale); LocaleService::GetInstance()->SetRequestedLocales(spoofLocale); @@ -91,17 +91,17 @@ TEST(Intl_Locale_LocaleService, GetWebExposedLocales) mozilla::Preferences::SetInt("privacy.spoof_english", 0); LocaleService::GetInstance()->GetWebExposedLocales(pvLocales); ASSERT_TRUE(pvLocales.Length() > 0); - ASSERT_TRUE(pvLocales[0].Equals(NS_LITERAL_CSTRING("de"))); + ASSERT_TRUE(pvLocales[0].Equals("de"_ns)); mozilla::Preferences::SetCString("intl.locale.privacy.web_exposed", "zh-TW"); LocaleService::GetInstance()->GetWebExposedLocales(pvLocales); ASSERT_TRUE(pvLocales.Length() > 0); - ASSERT_TRUE(pvLocales[0].Equals(NS_LITERAL_CSTRING("zh-TW"))); + ASSERT_TRUE(pvLocales[0].Equals("zh-TW"_ns)); mozilla::Preferences::SetInt("privacy.spoof_english", 2); LocaleService::GetInstance()->GetWebExposedLocales(pvLocales); ASSERT_EQ(1u, pvLocales.Length()); - ASSERT_TRUE(pvLocales[0].Equals(NS_LITERAL_CSTRING("en-US"))); + ASSERT_TRUE(pvLocales[0].Equals("en-US"_ns)); } TEST(Intl_Locale_LocaleService, GetRequestedLocales) diff --git a/intl/locale/tests/gtest/TestLocaleServiceNegotiate.cpp b/intl/locale/tests/gtest/TestLocaleServiceNegotiate.cpp index 67e1a462bd10..c428e81c8dc6 100644 --- a/intl/locale/tests/gtest/TestLocaleServiceNegotiate.cpp +++ b/intl/locale/tests/gtest/TestLocaleServiceNegotiate.cpp @@ -16,10 +16,10 @@ TEST(Intl_Locale_LocaleService, Negotiate) nsAutoCString defaultLocale("en-US"); int32_t strategy = LocaleService::kLangNegStrategyFiltering; - requestedLocales.AppendElement(NS_LITERAL_CSTRING("sr")); + requestedLocales.AppendElement("sr"_ns); - availableLocales.AppendElement(NS_LITERAL_CSTRING("sr-Cyrl")); - availableLocales.AppendElement(NS_LITERAL_CSTRING("sr-Latn")); + availableLocales.AppendElement("sr-Cyrl"_ns); + availableLocales.AppendElement("sr-Latn"_ns); LocaleService::GetInstance()->NegotiateLanguages( requestedLocales, availableLocales, defaultLocale, strategy, @@ -38,9 +38,9 @@ TEST(Intl_Locale_LocaleService, UseLSDefaultLocale) nsAutoCString defaultLocale("en-US"); int32_t strategy = LocaleService::kLangNegStrategyLookup; - requestedLocales.AppendElement(NS_LITERAL_CSTRING("sr")); + requestedLocales.AppendElement("sr"_ns); - availableLocales.AppendElement(NS_LITERAL_CSTRING("de")); + availableLocales.AppendElement("de"_ns); LocaleService::GetInstance()->NegotiateLanguages( requestedLocales, availableLocales, defaultLocale, strategy, diff --git a/intl/locale/windows/OSPreferences_win.cpp b/intl/locale/windows/OSPreferences_win.cpp index c06c9206b67d..ef6e8978633b 100644 --- a/intl/locale/windows/OSPreferences_win.cpp +++ b/intl/locale/windows/OSPreferences_win.cpp @@ -258,11 +258,11 @@ bool OSPreferences::ReadDateTimePattern(DateTimeFormatStyle aDateStyle, nsAString::const_iterator start, pos, end; start = str->BeginReading(pos); str->EndReading(end); - if (FindInReadable(NS_LITERAL_STRING("dddd"), pos, end)) { + if (FindInReadable(u"dddd"_ns, pos, end)) { str->ReplaceLiteral(pos - start, 4, u"EEEE"); } else { pos = start; - if (FindInReadable(NS_LITERAL_STRING("ddd"), pos, end)) { + if (FindInReadable(u"ddd"_ns, pos, end)) { str->ReplaceLiteral(pos - start, 3, u"EEE"); } } @@ -285,7 +285,7 @@ bool OSPreferences::ReadDateTimePattern(DateTimeFormatStyle aDateStyle, nsAString::const_iterator start, pos, end; start = aRetVal.BeginReading(pos); aRetVal.EndReading(end); - if (FindInReadable(NS_LITERAL_STRING("{1}"), pos, end)) { + if (FindInReadable(u"{1}"_ns, pos, end)) { aRetVal.Replace(pos - start, 3, tmpStr); } } @@ -325,7 +325,7 @@ bool OSPreferences::ReadDateTimePattern(DateTimeFormatStyle aDateStyle, nsAString::const_iterator start, pos, end; start = aRetVal.BeginReading(pos); aRetVal.EndReading(end); - if (FindInReadable(NS_LITERAL_STRING("{0}"), pos, end)) { + if (FindInReadable(u"{0}"_ns, pos, end)) { aRetVal.Replace(pos - start, 3, tmpStr); } } diff --git a/intl/strres/nsStringBundle.cpp b/intl/strres/nsStringBundle.cpp index 7116cb6c3209..f79c7eb9260f 100644 --- a/intl/strres/nsStringBundle.cpp +++ b/intl/strres/nsStringBundle.cpp @@ -451,7 +451,7 @@ nsresult nsStringBundleBase::ParseProperties(nsIPersistentProperties** aProps) { if (NS_FAILED(rv)) return rv; // It's a string bundle. We expect a text/plain type, so set that as hint - channel->SetContentType(NS_LITERAL_CSTRING("text/plain")); + channel->SetContentType("text/plain"_ns); rv = channel->Open(getter_AddRefs(in)); if (NS_FAILED(rv)) return rv; diff --git a/intl/uconv/nsTextToSubURI.cpp b/intl/uconv/nsTextToSubURI.cpp index ef84502aaa20..b293a93ec595 100644 --- a/intl/uconv/nsTextToSubURI.cpp +++ b/intl/uconv/nsTextToSubURI.cpp @@ -111,8 +111,7 @@ NS_IMETHODIMP nsTextToSubURI::UnEscapeURIForUI(const nsACString& aURIFragment, // in case of failure, return escaped URI // Test for != NS_OK rather than NS_FAILED, because incomplete multi-byte // sequences are also considered failure in this context - if (convertURItoUnicode(NS_LITERAL_CSTRING("UTF-8"), unescapedSpec, - _retval) != NS_OK) { + if (convertURItoUnicode("UTF-8"_ns, unescapedSpec, _retval) != NS_OK) { // assume UTF-8 instead of ASCII because hostname (IDN) may be in UTF-8 CopyUTF8toUTF16(aURIFragment, _retval); } diff --git a/ipc/glue/CrashReporterHost.cpp b/ipc/glue/CrashReporterHost.cpp index f3d5361cfa7e..8c2581486a10 100644 --- a/ipc/glue/CrashReporterHost.cpp +++ b/ipc/glue/CrashReporterHost.cpp @@ -201,8 +201,7 @@ void CrashReporterHost::NotifyCrashService(GeckoProcessType aProcessType, void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey, bool aValue) { - mExtraAnnotations[aKey] = - aValue ? NS_LITERAL_CSTRING("1") : NS_LITERAL_CSTRING("0"); + mExtraAnnotations[aKey] = aValue ? "1"_ns : "0"_ns; } void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey, diff --git a/ipc/glue/ForkServer.cpp b/ipc/glue/ForkServer.cpp index 4a69ec38a457..24a0723d0e64 100644 --- a/ipc/glue/ForkServer.cpp +++ b/ipc/glue/ForkServer.cpp @@ -291,8 +291,7 @@ bool ForkServer::RunForkServer(int* aArgc, char*** aArgv) { forkserver.mAppProcBuilder->InitAppProcess(aArgc, aArgv); forkserver.mAppProcBuilder.reset(); - MOZ_ASSERT(NS_LITERAL_CSTRING("tab") == (*aArgv)[*aArgc - 1], - "Only |tab| is allowed!"); + MOZ_ASSERT("tab"_ns == (*aArgv)[*aArgc - 1], "Only |tab| is allowed!"); // Open log files again with right names and the new PID. nsTraceRefcnt::ResetLogFiles((*aArgv)[*aArgc - 1]); diff --git a/ipc/glue/GeckoChildProcessHost.cpp b/ipc/glue/GeckoChildProcessHost.cpp index 32a67dcda826..2933e0fcaf22 100644 --- a/ipc/glue/GeckoChildProcessHost.cpp +++ b/ipc/glue/GeckoChildProcessHost.cpp @@ -530,9 +530,9 @@ mozilla::BinPathType BaseProcessLauncher::GetPathToBinary( // We need to use an App Bundle on OS X so that we can hide // the dock icon. See Bug 557225. - childProcPath->AppendNative(NS_LITERAL_CSTRING("plugin-container.app")); - childProcPath->AppendNative(NS_LITERAL_CSTRING("Contents")); - childProcPath->AppendNative(NS_LITERAL_CSTRING("MacOS")); + childProcPath->AppendNative("plugin-container.app"_ns); + childProcPath->AppendNative("Contents"_ns); + childProcPath->AppendNative("MacOS"_ns); nsCString tempCPath; childProcPath->GetNativePath(tempCPath); exePath = FilePath(tempCPath.get()); @@ -924,8 +924,7 @@ nsCOMPtr GetIPCLauncher() { StaticMutexAutoLock lock(gIPCLaunchThreadMutex); if (!gIPCLaunchThread) { nsCOMPtr thread; - nsresult rv = NS_NewNamedThread(NS_LITERAL_CSTRING("IPC Launch"), - getter_AddRefs(thread)); + nsresult rv = NS_NewNamedThread("IPC Launch"_ns, getter_AddRefs(thread)); if (!NS_WARN_IF(NS_FAILED(rv))) { NS_DispatchToMainThread( NS_NewRunnableFunction("GeckoChildProcessHost::GetIPCLauncher", [] { @@ -950,7 +949,7 @@ nsCOMPtr GetIPCLauncher() { nsCOMPtr GetIPCLauncher() { nsCOMPtr pool = - mozilla::SharedThreadPool::Get(NS_LITERAL_CSTRING("IPC Launch")); + mozilla::SharedThreadPool::Get("IPC Launch"_ns); MOZ_DIAGNOSTIC_ASSERT(pool); return pool; } diff --git a/ipc/glue/IPCMessageUtils.h b/ipc/glue/IPCMessageUtils.h index 54235cf95f20..f0b43373f9a3 100644 --- a/ipc/glue/IPCMessageUtils.h +++ b/ipc/glue/IPCMessageUtils.h @@ -129,13 +129,11 @@ struct EnumSerializer { uintParamType value; if (!ReadParam(aMsg, aIter, &value)) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IPCReadErrorReason, - NS_LITERAL_CSTRING("Bad iter")); + CrashReporter::Annotation::IPCReadErrorReason, "Bad iter"_ns); return false; } else if (!EnumValidator::IsLegalValue(paramType(value))) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::IPCReadErrorReason, - NS_LITERAL_CSTRING("Illegal value")); + CrashReporter::Annotation::IPCReadErrorReason, "Illegal value"_ns); return false; } *aResult = paramType(value); diff --git a/ipc/glue/IdleSchedulerParent.cpp b/ipc/glue/IdleSchedulerParent.cpp index 4b6683128373..4202c02b20bc 100644 --- a/ipc/glue/IdleSchedulerParent.cpp +++ b/ipc/glue/IdleSchedulerParent.cpp @@ -46,8 +46,8 @@ IdleSchedulerParent::IdleSchedulerParent() { do_GetService(NS_SYSTEMINFO_CONTRACTID); if (infoService) { int32_t cpus; - nsresult rv = infoService->GetPropertyAsInt32( - NS_LITERAL_STRING("cpucount"), &cpus); + nsresult rv = + infoService->GetPropertyAsInt32(u"cpucount"_ns, &cpus); if (NS_SUCCEEDED(rv) && cpus > 1) { sCPUsForChildProcesses = cpus - 1; } diff --git a/ipc/glue/LibrarySandboxPreload.cpp b/ipc/glue/LibrarySandboxPreload.cpp index 9c826ab7c2d8..2f6ff794e2de 100644 --- a/ipc/glue/LibrarySandboxPreload.cpp +++ b/ipc/glue/LibrarySandboxPreload.cpp @@ -43,12 +43,12 @@ static nsAutoCString GetSandboxedPath(const nsACString& libName) { nsAutoCString GetSandboxedGraphitePath() { return GetSandboxedPath( - NS_LITERAL_CSTRING(MOZ_DLL_PREFIX "graphitewasm" MOZ_DLL_SUFFIX)); + nsLiteralCString(MOZ_DLL_PREFIX "graphitewasm" MOZ_DLL_SUFFIX)); } nsAutoCString GetSandboxedOggPath() { return GetSandboxedPath( - NS_LITERAL_CSTRING(MOZ_DLL_PREFIX "oggwasm" MOZ_DLL_SUFFIX)); + nsLiteralCString(MOZ_DLL_PREFIX "oggwasm" MOZ_DLL_SUFFIX)); } PRLibrary* PreloadLibrary(const nsAutoCString& path) { diff --git a/ipc/glue/ProtocolUtils.cpp b/ipc/glue/ProtocolUtils.cpp index 2033ed459fe3..d73a0c6a2235 100644 --- a/ipc/glue/ProtocolUtils.cpp +++ b/ipc/glue/ProtocolUtils.cpp @@ -86,7 +86,7 @@ bool DuplicateHandle(HANDLE aSourceHandle, DWORD aTargetProcessId, if (!targetProcess) { CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::IPCTransportFailureReason, - NS_LITERAL_CSTRING("Failed to open target process.")); + "Failed to open target process."_ns); return false; } diff --git a/ipc/glue/ScopedXREEmbed.cpp b/ipc/glue/ScopedXREEmbed.cpp index 24c0132f3594..c83bf7e17551 100644 --- a/ipc/glue/ScopedXREEmbed.cpp +++ b/ipc/glue/ScopedXREEmbed.cpp @@ -69,7 +69,7 @@ void ScopedXREEmbed::Start() { localFile = parent; NS_ENSURE_TRUE_VOID(localFile); - rv = localFile->SetNativeLeafName(NS_LITERAL_CSTRING("Resources")); + rv = localFile->SetNativeLeafName("Resources"_ns); if (NS_FAILED(rv)) { return; } diff --git a/ipc/glue/WindowsMessageLoop.cpp b/ipc/glue/WindowsMessageLoop.cpp index 681ad702dfcd..a1cd9dea9850 100644 --- a/ipc/glue/WindowsMessageLoop.cpp +++ b/ipc/glue/WindowsMessageLoop.cpp @@ -458,8 +458,8 @@ static bool WindowIsDeferredWindow(HWND hWnd) { // Common mozilla windows we must defer messages to. nsDependentString className(buffer, length); - if (StringBeginsWith(className, NS_LITERAL_STRING("Mozilla")) || - StringBeginsWith(className, NS_LITERAL_STRING("Gecko")) || + if (StringBeginsWith(className, u"Mozilla"_ns) || + StringBeginsWith(className, u"Gecko"_ns) || className.EqualsLiteral("nsToolkitClass") || className.EqualsLiteral("nsAppShell:EventWindowClass")) { return true; diff --git a/ipc/mscom/COMPtrHolder.h b/ipc/mscom/COMPtrHolder.h index ee807e838c10..83c1f85de975 100644 --- a/ipc/mscom/COMPtrHolder.h +++ b/ipc/mscom/COMPtrHolder.h @@ -183,8 +183,7 @@ struct ParamTraits> { mozilla::mscom::ProxyStream proxyStream(_IID, buf.get(), length, &env); if (!proxyStream.IsValid()) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::ProxyStreamValid, - NS_LITERAL_CSTRING("false")); + CrashReporter::Annotation::ProxyStreamValid, "false"_ns); return false; } diff --git a/ipc/mscom/ProxyStream.cpp b/ipc/mscom/ProxyStream.cpp index 80a0ba037aff..f1af6c75a70d 100644 --- a/ipc/mscom/ProxyStream.cpp +++ b/ipc/mscom/ProxyStream.cpp @@ -45,8 +45,7 @@ ProxyStream::ProxyStream(REFIID aIID, const BYTE* aInitBuf, CrashReporter::Annotation::ProxyStreamUnmarshalStatus; if (!aInitBufSize) { - CrashReporter::AnnotateCrashReport(kCrashReportKey, - NS_LITERAL_CSTRING("!aInitBufSize")); + CrashReporter::AnnotateCrashReport(kCrashReportKey, "!aInitBufSize"_ns); // We marshaled a nullptr. Nothing else to do here. return; } @@ -64,8 +63,7 @@ ProxyStream::ProxyStream(REFIID aIID, const BYTE* aInitBuf, // in that case, even though marshaling a nullptr is allowable. MOZ_ASSERT(mStream); if (!mStream) { - CrashReporter::AnnotateCrashReport(kCrashReportKey, - NS_LITERAL_CSTRING("!mStream")); + CrashReporter::AnnotateCrashReport(kCrashReportKey, "!mStream"_ns); return; } @@ -141,8 +139,8 @@ ProxyStream::ProxyStream(REFIID aIID, const BYTE* aInitBuf, CrashReporter::Annotation::CoUnmarshalInterfaceResult, hrAsStr); AnnotateInterfaceRegistration(aIID); if (!mUnmarshaledProxy) { - CrashReporter::AnnotateCrashReport( - kCrashReportKey, NS_LITERAL_CSTRING("!mUnmarshaledProxy")); + CrashReporter::AnnotateCrashReport(kCrashReportKey, + "!mUnmarshaledProxy"_ns); } #if defined(ACCESSIBILITY) @@ -154,8 +152,7 @@ ProxyStream::ProxyStream(REFIID aIID, const BYTE* aInitBuf, NS_ConvertUTF16toUTF8(manifestPath)); CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::A11yHandlerRegistered, - a11y::IsHandlerRegistered() ? NS_LITERAL_CSTRING("true") - : NS_LITERAL_CSTRING("false")); + a11y::IsHandlerRegistered() ? "true"_ns : "false"_ns); CrashReporter::AnnotateCrashReport( CrashReporter::Annotation::ExpectedStreamLen, expectedStreamLen); @@ -379,8 +376,7 @@ ProxyStream::ProxyStream(REFIID aIID, IUnknown* aObject, Environment* aEnv, if (streamSize) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::ProxyStreamSizeFrom, - NS_LITERAL_CSTRING("IStream::Stat")); + CrashReporter::Annotation::ProxyStreamSizeFrom, "IStream::Stat"_ns); mBufSize = streamSize; } @@ -396,8 +392,7 @@ ProxyStream::ProxyStream(REFIID aIID, IUnknown* aObject, Environment* aEnv, // be larger than the actual stream size. if (!streamSize) { CrashReporter::AnnotateCrashReport( - CrashReporter::Annotation::ProxyStreamSizeFrom, - NS_LITERAL_CSTRING("GlobalSize")); + CrashReporter::Annotation::ProxyStreamSizeFrom, "GlobalSize"_ns); mBufSize = static_cast(::GlobalSize(hglobal)); } diff --git a/ipc/mscom/Utils.cpp b/ipc/mscom/Utils.cpp index daa5e037b271..ab6ac719696b 100644 --- a/ipc/mscom/Utils.cpp +++ b/ipc/mscom/Utils.cpp @@ -419,9 +419,9 @@ bool IsClassThreadAwareInprocServer(REFCLSID aClsid) { nsAutoString strClsid; GUIDToString(aClsid, strClsid); - nsAutoString inprocServerSubkey(NS_LITERAL_STRING("CLSID\\")); + nsAutoString inprocServerSubkey(u"CLSID\\"_ns); inprocServerSubkey.Append(strClsid); - inprocServerSubkey.Append(NS_LITERAL_STRING("\\InprocServer32")); + inprocServerSubkey.Append(u"\\InprocServer32"_ns); // Of the possible values, "Apartment" is the longest, so we'll make this // buffer large enough to hold that one. diff --git a/js/xpconnect/loader/ScriptPreloader.cpp b/js/xpconnect/loader/ScriptPreloader.cpp index cbe09f5c6515..67b8d4ccc246 100644 --- a/js/xpconnect/loader/ScriptPreloader.cpp +++ b/js/xpconnect/loader/ScriptPreloader.cpp @@ -145,7 +145,7 @@ ScriptPreloader& ScriptPreloader::GetChildSingleton() { if (!singleton) { singleton = new ScriptPreloader(); if (XRE_IsParentProcess()) { - Unused << singleton->InitCache(NS_LITERAL_STRING("scriptCache-child")); + Unused << singleton->InitCache(u"scriptCache-child"_ns); } ClearOnShutdown(&singleton); } @@ -384,7 +384,7 @@ Result, nsresult> ScriptPreloader::GetCacheFile( nsCOMPtr cacheFile; MOZ_TRY(mProfD->Clone(getter_AddRefs(cacheFile))); - MOZ_TRY(cacheFile->AppendNative(NS_LITERAL_CSTRING("startupCache"))); + MOZ_TRY(cacheFile->AppendNative("startupCache"_ns)); Unused << cacheFile->Create(nsIFile::DIRECTORY_TYPE, 0777); MOZ_TRY(cacheFile->Append(mBaseName + suffix)); @@ -398,16 +398,14 @@ Result ScriptPreloader::OpenCache() { MOZ_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD))); nsCOMPtr cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING(".bin"))); + MOZ_TRY_VAR(cacheFile, GetCacheFile(u".bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); if (exists) { - MOZ_TRY(cacheFile->MoveTo(nullptr, - mBaseName + NS_LITERAL_STRING("-current.bin"))); + MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + u"-current.bin"_ns)); } else { - MOZ_TRY( - cacheFile->SetLeafName(mBaseName + NS_LITERAL_STRING("-current.bin"))); + MOZ_TRY(cacheFile->SetLeafName(mBaseName + u"-current.bin"_ns)); MOZ_TRY(cacheFile->Exists(&exists)); if (!exists) { return Err(NS_ERROR_FILE_NOT_FOUND); @@ -660,7 +658,7 @@ Result ScriptPreloader::WriteCache() { } nsCOMPtr cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING("-new.bin"))); + MOZ_TRY_VAR(cacheFile, GetCacheFile(u"-new.bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); @@ -712,7 +710,7 @@ Result ScriptPreloader::WriteCache() { } } - MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + NS_LITERAL_STRING(".bin"))); + MOZ_TRY(cacheFile->MoveTo(nullptr, mBaseName + u".bin"_ns)); return Ok(); } diff --git a/js/xpconnect/loader/ScriptPreloader.h b/js/xpconnect/loader/ScriptPreloader.h index c98e866cd546..a26388dcffe4 100644 --- a/js/xpconnect/loader/ScriptPreloader.h +++ b/js/xpconnect/loader/ScriptPreloader.h @@ -96,8 +96,7 @@ class ScriptPreloader : public nsIObserver, TimeStamp loadTime); // Initializes the script cache from the startup script cache file. - Result InitCache( - const nsAString& = NS_LITERAL_STRING("scriptCache")); + Result InitCache(const nsAString& = u"scriptCache"_ns); Result InitCache(const Maybe& cacheFile, ScriptCacheChild* cacheChild); diff --git a/js/xpconnect/loader/URLPreloader.cpp b/js/xpconnect/loader/URLPreloader.cpp index 54c85d070423..aa79ccd5eddd 100644 --- a/js/xpconnect/loader/URLPreloader.cpp +++ b/js/xpconnect/loader/URLPreloader.cpp @@ -68,8 +68,8 @@ nsresult URLPreloader::CollectReports(nsIHandleReportCallback* aHandleReport, aHandleReport->Callback( EmptyCString(), path, KIND_HEAP, UNITS_BYTES, elem->SizeOfIncludingThis(MallocSizeOf), - NS_LITERAL_CSTRING("Memory used to hold cache data for files which " - "have been read or pre-loaded during this session."), + nsLiteralCString("Memory used to hold cache data for files which " + "have been read or pre-loaded during this session."), aData); } @@ -156,10 +156,10 @@ Result, nsresult> URLPreloader::GetCacheFile( nsCOMPtr cacheFile; MOZ_TRY(mProfD->Clone(getter_AddRefs(cacheFile))); - MOZ_TRY(cacheFile->AppendNative(NS_LITERAL_CSTRING("startupCache"))); + MOZ_TRY(cacheFile->AppendNative("startupCache"_ns)); Unused << cacheFile->Create(nsIFile::DIRECTORY_TYPE, 0777); - MOZ_TRY(cacheFile->Append(NS_LITERAL_STRING("urlCache") + suffix)); + MOZ_TRY(cacheFile->Append(u"urlCache"_ns + suffix)); return std::move(cacheFile); } @@ -168,15 +168,14 @@ static const uint8_t URL_MAGIC[] = "mozURLcachev002"; Result, nsresult> URLPreloader::FindCacheFile() { nsCOMPtr cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING(".bin"))); + MOZ_TRY_VAR(cacheFile, GetCacheFile(u".bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); if (exists) { - MOZ_TRY( - cacheFile->MoveTo(nullptr, NS_LITERAL_STRING("urlCache-current.bin"))); + MOZ_TRY(cacheFile->MoveTo(nullptr, u"urlCache-current.bin"_ns)); } else { - MOZ_TRY(cacheFile->SetLeafName(NS_LITERAL_STRING("urlCache-current.bin"))); + MOZ_TRY(cacheFile->SetLeafName(u"urlCache-current.bin"_ns)); MOZ_TRY(cacheFile->Exists(&exists)); if (!exists) { return Err(NS_ERROR_FILE_NOT_FOUND); @@ -204,7 +203,7 @@ Result URLPreloader::WriteCache() { LOG(Debug, "Writing cache..."); nsCOMPtr cacheFile; - MOZ_TRY_VAR(cacheFile, GetCacheFile(NS_LITERAL_STRING("-new.bin"))); + MOZ_TRY_VAR(cacheFile, GetCacheFile(u"-new.bin"_ns)); bool exists; MOZ_TRY(cacheFile->Exists(&exists)); @@ -239,7 +238,7 @@ Result URLPreloader::WriteCache() { MOZ_TRY(Write(fd, buf.Get(), buf.cursor())); } - MOZ_TRY(cacheFile->MoveTo(nullptr, NS_LITERAL_STRING("urlCache.bin"))); + MOZ_TRY(cacheFile->MoveTo(nullptr, u"urlCache.bin"_ns)); NS_DispatchToMainThread( NewRunnableMethod("URLPreloader::Cleanup", this, &URLPreloader::Cleanup)); diff --git a/js/xpconnect/loader/mozJSComponentLoader.cpp b/js/xpconnect/loader/mozJSComponentLoader.cpp index 90f188b94377..4a27ea405961 100644 --- a/js/xpconnect/loader/mozJSComponentLoader.cpp +++ b/js/xpconnect/loader/mozJSComponentLoader.cpp @@ -347,7 +347,7 @@ static nsresult AnnotateScriptContents(CrashReporter::Annotation aName, // shouldn't have any here, but if we do because of data corruption, we // still want the annotation. So replace any embedded nuls before // annotating. - str.ReplaceSubstring(NS_LITERAL_CSTRING("\0"), NS_LITERAL_CSTRING("\\0")); + str.ReplaceSubstring("\0"_ns, "\\0"_ns); CrashReporter::AnnotateCrashReport(aName, str); @@ -357,11 +357,11 @@ static nsresult AnnotateScriptContents(CrashReporter::Annotation aName, nsresult mozJSComponentLoader::AnnotateCrashReport() { Unused << AnnotateScriptContents( CrashReporter::Annotation::nsAsyncShutdownComponent, - NS_LITERAL_CSTRING("resource://gre/components/nsAsyncShutdown.js")); + "resource://gre/components/nsAsyncShutdown.js"_ns); Unused << AnnotateScriptContents( CrashReporter::Annotation::AsyncShutdownModule, - NS_LITERAL_CSTRING("resource://gre/modules/AsyncShutdown.jsm")); + "resource://gre/modules/AsyncShutdown.jsm"_ns); return NS_OK; } @@ -401,8 +401,7 @@ const mozilla::Module* mozJSComponentLoader::LoadModule(FileLocation& aFile) { jsapi.Init(); JSContext* cx = jsapi.cx(); - bool isCriticalModule = - StringEndsWith(spec, NS_LITERAL_CSTRING("/nsAsyncShutdown.js")); + bool isCriticalModule = StringEndsWith(spec, "/nsAsyncShutdown.js"_ns); auto entry = MakeUnique(RootingContext::get(cx)); RootedValue exn(cx); @@ -589,8 +588,7 @@ void mozJSComponentLoader::CreateLoaderGlobal(JSContext* aCx, JSObject* mozJSComponentLoader::GetSharedGlobal(JSContext* aCx) { if (!mLoaderGlobal) { JS::RootedObject globalObj(aCx); - CreateLoaderGlobal(aCx, NS_LITERAL_CSTRING("shared JSM global"), - &globalObj); + CreateLoaderGlobal(aCx, "shared JSM global"_ns, &globalObj); // If we fail to create a module global this early, we're not going to // get very far, so just bail out now. diff --git a/js/xpconnect/loader/mozJSSubScriptLoader.cpp b/js/xpconnect/loader/mozJSSubScriptLoader.cpp index d2b6de54864e..853e30bc2f39 100644 --- a/js/xpconnect/loader/mozJSSubScriptLoader.cpp +++ b/js/xpconnect/loader/mozJSSubScriptLoader.cpp @@ -264,7 +264,7 @@ bool mozJSSubScriptLoader::ReadScript(JS::MutableHandle script, nsIRequest::LOAD_NORMAL, serv); if (NS_SUCCEEDED(rv)) { - chan->SetContentType(NS_LITERAL_CSTRING("application/javascript")); + chan->SetContentType("application/javascript"_ns); rv = chan->Open(getter_AddRefs(instream)); } @@ -394,7 +394,7 @@ nsresult mozJSSubScriptLoader::DoLoadSubScriptWithOptions( nsCOMPtr serv = do_GetService(NS_IOSERVICE_CONTRACTID); if (!serv) { - ReportError(cx, NS_LITERAL_CSTRING(LOAD_ERROR_NOSERVICE)); + ReportError(cx, nsLiteralCString(LOAD_ERROR_NOSERVICE)); return NS_OK; } @@ -408,13 +408,13 @@ nsresult mozJSSubScriptLoader::DoLoadSubScriptWithOptions( // canonicalized spec. rv = NS_NewURI(getter_AddRefs(uri), asciiUrl); if (NS_FAILED(rv)) { - ReportError(cx, NS_LITERAL_CSTRING(LOAD_ERROR_NOURI)); + ReportError(cx, nsLiteralCString(LOAD_ERROR_NOURI)); return NS_OK; } rv = uri->GetSpec(uriStr); if (NS_FAILED(rv)) { - ReportError(cx, NS_LITERAL_CSTRING(LOAD_ERROR_NOSPEC)); + ReportError(cx, nsLiteralCString(LOAD_ERROR_NOSPEC)); return NS_OK; } diff --git a/js/xpconnect/src/Sandbox.cpp b/js/xpconnect/src/Sandbox.cpp index e3275cb79929..0c45fe3f5f8e 100644 --- a/js/xpconnect/src/Sandbox.cpp +++ b/js/xpconnect/src/Sandbox.cpp @@ -1111,7 +1111,7 @@ nsresult ApplyAddonContentScriptCSP(nsISupports* prinOrSop) { } nsString url; - MOZ_TRY_VAR(url, addonPolicy->GetURL(NS_LITERAL_STRING(""))); + MOZ_TRY_VAR(url, addonPolicy->GetURL(u""_ns)); nsCOMPtr selfURI; MOZ_TRY(NS_NewURI(getter_AddRefs(selfURI), url)); @@ -1833,7 +1833,7 @@ static nsresult AssembleSandboxMemoryReporterName(JSContext* cx, nsCString& sandboxName) { // Use a default name when the caller did not provide a sandboxName. if (sandboxName.IsEmpty()) { - sandboxName = NS_LITERAL_CSTRING("[anonymous sandbox]"); + sandboxName = "[anonymous sandbox]"_ns; } else { #ifndef DEBUG // Adding the caller location is fairly expensive, so in non-debug diff --git a/js/xpconnect/src/XPCConvert.cpp b/js/xpconnect/src/XPCConvert.cpp index 3ecd8bf672d0..5128fb69b44a 100644 --- a/js/xpconnect/src/XPCConvert.cpp +++ b/js/xpconnect/src/XPCConvert.cpp @@ -1191,8 +1191,7 @@ static nsresult JSErrorToXPCException(JSContext* cx, const char* toStringResult, bestMessage, NS_ConvertASCIItoUTF16(report->filename), linebuf ? nsDependentString(linebuf, report->linebufLength()) : EmptyString(), - report->lineno, report->tokenOffset(), flags, - NS_LITERAL_CSTRING("XPConnect JavaScript"), + report->lineno, report->tokenOffset(), flags, "XPConnect JavaScript"_ns, nsJSUtils::GetCurrentlyRunningCodeInnerWindowID(cx)); } diff --git a/js/xpconnect/src/XPCJSRuntime.cpp b/js/xpconnect/src/XPCJSRuntime.cpp index 0667bd99db8d..b6684ec62a62 100644 --- a/js/xpconnect/src/XPCJSRuntime.cpp +++ b/js/xpconnect/src/XPCJSRuntime.cpp @@ -271,7 +271,7 @@ static bool TryParseLocationURICandidate( // object, which we can't allow while we're iterating over the JS heap. // So just skip any such URL. // -- GROSS HACK ALERT -- - if (StringBeginsWith(uristr, NS_LITERAL_CSTRING("xb"))) { + if (StringBeginsWith(uristr, "xb"_ns)) { return false; } } @@ -349,7 +349,7 @@ bool RealmPrivate::TryParseLocationURI(RealmPrivate::LocationHint aLocationHint, // item that is actually a URI. // First, hack off the :) part as well - int32_t ridx = location.RFind(NS_LITERAL_CSTRING(":")); + int32_t ridx = location.RFind(":"_ns); nsAutoCString chain( Substring(location, idx + fromLength, ridx - idx - fromLength)); @@ -938,7 +938,7 @@ void XPCJSRuntime::CustomOutOfMemoryCallback() { } // If this fails, it fails silently. - dumper->DumpMemoryInfoToTempDir(NS_LITERAL_STRING("due-to-JS-OOM"), + dumper->DumpMemoryInfoToTempDir(u"due-to-JS-OOM"_ns, /* anonymize = */ false, /* minimizeMemoryUsage = */ false); } @@ -1269,7 +1269,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) #define REPORT(_path, _kind, _units, _amount, _desc) \ handleReport->Callback(EmptyCString(), _path, nsIMemoryReporter::_kind, \ nsIMemoryReporter::_units, _amount, \ - NS_LITERAL_CSTRING(_desc), data); + nsLiteralCString(_desc), data); #define REPORT_BYTES(_path, _kind, _amount, _desc) \ REPORT(_path, _kind, UNITS_BYTES, _amount, _desc); @@ -1280,7 +1280,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) handleReport->Callback(EmptyCString(), _path, \ nsIMemoryReporter::KIND_NONHEAP, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ gcTotal += amount; \ } while (0) @@ -1294,7 +1294,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) handleReport->Callback(EmptyCString(), _path, \ nsIMemoryReporter::KIND_HEAP, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ } else { \ sundriesMallocHeap += amount; \ } \ @@ -1308,7 +1308,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) handleReport->Callback(EmptyCString(), _path, \ nsIMemoryReporter::KIND_NONHEAP, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ gcTotal += amount; \ } else { \ sundriesGCHeap += amount; \ @@ -1323,7 +1323,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) handleReport->Callback(EmptyCString(), _path, \ nsIMemoryReporter::KIND_NONHEAP, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ } else { \ sundriesNonHeap += amount; \ } \ @@ -1335,7 +1335,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) size_t amount = _amount; /* evaluate _amount only once */ \ handleReport->Callback(EmptyCString(), _path, nsIMemoryReporter::_kind, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ rtTotal += amount; \ } while (0) @@ -1345,7 +1345,7 @@ NS_IMPL_ISUPPORTS(JSMainRuntimeTemporaryPeakReporter, nsIMemoryReporter) size_t amount = _amount; /* evaluate _amount only once */ \ handleReport->Callback(EmptyCString(), _path, nsIMemoryReporter::_kind, \ nsIMemoryReporter::UNITS_BYTES, amount, \ - NS_LITERAL_CSTRING(_desc), data); \ + nsLiteralCString(_desc), data); \ gcThingTotal += amount; \ } while (0) @@ -1366,101 +1366,90 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, MOZ_ASSERT(!gcTotalOut == zStats.isTotals); - ZRREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("symbols/gc-heap"), - zStats.symbolsGCHeap, "Symbols."); + ZRREPORT_GC_BYTES(pathPrefix + "symbols/gc-heap"_ns, zStats.symbolsGCHeap, + "Symbols."); ZRREPORT_GC_BYTES( - pathPrefix + NS_LITERAL_CSTRING("gc-heap-arena-admin"), - zStats.gcHeapArenaAdmin, + pathPrefix + "gc-heap-arena-admin"_ns, zStats.gcHeapArenaAdmin, "Bookkeeping information and alignment padding within GC arenas."); - ZRREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("unused-gc-things"), + ZRREPORT_GC_BYTES(pathPrefix + "unused-gc-things"_ns, zStats.unusedGCThings.totalSize(), "Unused GC thing cells within non-empty arenas."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("unique-id-map"), - zStats.uniqueIdMap, "Address-independent cell identities."); + ZRREPORT_BYTES(pathPrefix + "unique-id-map"_ns, zStats.uniqueIdMap, + "Address-independent cell identities."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("shape-tables"), - zStats.shapeTables, "Tables storing shape information."); + ZRREPORT_BYTES(pathPrefix + "shape-tables"_ns, zStats.shapeTables, + "Tables storing shape information."); - ZRREPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("compartments/compartment-objects"), - zStats.compartmentObjects, "The JS::Compartment objects in this zone."); + ZRREPORT_BYTES(pathPrefix + "compartments/compartment-objects"_ns, + zStats.compartmentObjects, + "The JS::Compartment objects in this zone."); ZRREPORT_BYTES( - pathPrefix + - NS_LITERAL_CSTRING("compartments/cross-compartment-wrapper-tables"), + pathPrefix + "compartments/cross-compartment-wrapper-tables"_ns, zStats.crossCompartmentWrappersTables, "The cross-compartment wrapper tables."); ZRREPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("compartments/private-data"), + pathPrefix + "compartments/private-data"_ns, zStats.compartmentsPrivateData, "Extra data attached to each compartment by XPConnect, including " "its wrapped-js."); - ZRREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("jit-codes-gc-heap"), - zStats.jitCodesGCHeap, + ZRREPORT_GC_BYTES(pathPrefix + "jit-codes-gc-heap"_ns, zStats.jitCodesGCHeap, "References to executable code pools used by the JITs."); ZRREPORT_GC_BYTES( - pathPrefix + NS_LITERAL_CSTRING("object-groups/gc-heap"), - zStats.objectGroupsGCHeap, + pathPrefix + "object-groups/gc-heap"_ns, zStats.objectGroupsGCHeap, "Classification and type inference information about objects."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("object-groups/malloc-heap"), + ZRREPORT_BYTES(pathPrefix + "object-groups/malloc-heap"_ns, zStats.objectGroupsMallocHeap, "Object group addenda."); - ZRREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("scopes/gc-heap"), - zStats.scopesGCHeap, "Scope information for scripts."); + ZRREPORT_GC_BYTES(pathPrefix + "scopes/gc-heap"_ns, zStats.scopesGCHeap, + "Scope information for scripts."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("scopes/malloc-heap"), - zStats.scopesMallocHeap, + ZRREPORT_BYTES(pathPrefix + "scopes/malloc-heap"_ns, zStats.scopesMallocHeap, "Arrays of binding names and other binding-related data."); - ZRREPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("regexp-shareds/gc-heap"), + ZRREPORT_GC_BYTES(pathPrefix + "regexp-shareds/gc-heap"_ns, zStats.regExpSharedsGCHeap, "Shared compiled regexp data."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("regexp-shareds/malloc-heap"), + ZRREPORT_BYTES(pathPrefix + "regexp-shareds/malloc-heap"_ns, zStats.regExpSharedsMallocHeap, "Shared compiled regexp data."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("type-pool"), zStats.typePool, + ZRREPORT_BYTES(pathPrefix + "type-pool"_ns, zStats.typePool, "Type sets and related data."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("regexp-zone"), - zStats.regexpZone, "The regexp zone and regexp data."); + ZRREPORT_BYTES(pathPrefix + "regexp-zone"_ns, zStats.regexpZone, + "The regexp zone and regexp data."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("jit-zone"), zStats.jitZone, - "The JIT zone."); + ZRREPORT_BYTES(pathPrefix + "jit-zone"_ns, zStats.jitZone, "The JIT zone."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("baseline/optimized-stubs"), + ZRREPORT_BYTES(pathPrefix + "baseline/optimized-stubs"_ns, zStats.baselineStubsOptimized, "The Baseline JIT's optimized IC stubs (excluding code)."); - ZRREPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("script-counts-map"), - zStats.scriptCountsMap, + ZRREPORT_BYTES(pathPrefix + "script-counts-map"_ns, zStats.scriptCountsMap, "Profiling-related information for scripts."); - ZRREPORT_NONHEAP_BYTES(pathPrefix + NS_LITERAL_CSTRING("code/ion"), - zStats.code.ion, + ZRREPORT_NONHEAP_BYTES(pathPrefix + "code/ion"_ns, zStats.code.ion, "Code generated by the IonMonkey JIT."); - ZRREPORT_NONHEAP_BYTES(pathPrefix + NS_LITERAL_CSTRING("code/baseline"), - zStats.code.baseline, + ZRREPORT_NONHEAP_BYTES(pathPrefix + "code/baseline"_ns, zStats.code.baseline, "Code generated by the Baseline JIT."); - ZRREPORT_NONHEAP_BYTES(pathPrefix + NS_LITERAL_CSTRING("code/regexp"), - zStats.code.regexp, + ZRREPORT_NONHEAP_BYTES(pathPrefix + "code/regexp"_ns, zStats.code.regexp, "Code generated by the regexp JIT."); ZRREPORT_NONHEAP_BYTES( - pathPrefix + NS_LITERAL_CSTRING("code/other"), zStats.code.other, + pathPrefix + "code/other"_ns, zStats.code.other, "Code generated by the JITs for wrappers and trampolines."); - ZRREPORT_NONHEAP_BYTES(pathPrefix + NS_LITERAL_CSTRING("code/unused"), - zStats.code.unused, + ZRREPORT_NONHEAP_BYTES(pathPrefix + "code/unused"_ns, zStats.code.unused, "Memory allocated by one of the JITs to hold code, " "but which is currently unused."); @@ -1491,7 +1480,7 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, // To avoid cluttering up about:memory like this, we stick notable // strings which contain "string(length=" into their own bucket. #define STRING_LENGTH "string(length=" - if (FindInReadable(NS_LITERAL_CSTRING(STRING_LENGTH), notableString)) { + if (FindInReadable(nsLiteralCString(STRING_LENGTH), notableString)) { stringsNotableAboutMemoryGCHeap += info.gcHeapLatin1; stringsNotableAboutMemoryGCHeap += info.gcHeapTwoByte; stringsNotableAboutMemoryMallocHeap += info.mallocHeapLatin1; @@ -1514,64 +1503,61 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, truncated ? " (truncated)" : ""); if (info.gcHeapLatin1 > 0) { - REPORT_GC_BYTES(path + NS_LITERAL_CSTRING("gc-heap/latin1"), - info.gcHeapLatin1, "Latin1 strings. " MAYBE_INLINE); + REPORT_GC_BYTES(path + "gc-heap/latin1"_ns, info.gcHeapLatin1, + "Latin1 strings. " MAYBE_INLINE); } if (info.gcHeapTwoByte > 0) { - REPORT_GC_BYTES(path + NS_LITERAL_CSTRING("gc-heap/two-byte"), - info.gcHeapTwoByte, "TwoByte strings. " MAYBE_INLINE); + REPORT_GC_BYTES(path + "gc-heap/two-byte"_ns, info.gcHeapTwoByte, + "TwoByte strings. " MAYBE_INLINE); } if (info.mallocHeapLatin1 > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("malloc-heap/latin1"), KIND_HEAP, + REPORT_BYTES(path + "malloc-heap/latin1"_ns, KIND_HEAP, info.mallocHeapLatin1, "Non-inline Latin1 string characters. " MAYBE_OVERALLOCATED); } if (info.mallocHeapTwoByte > 0) { REPORT_BYTES( - path + NS_LITERAL_CSTRING("malloc-heap/two-byte"), KIND_HEAP, - info.mallocHeapTwoByte, + path + "malloc-heap/two-byte"_ns, KIND_HEAP, info.mallocHeapTwoByte, "Non-inline TwoByte string characters. " MAYBE_OVERALLOCATED); } } nsCString nonNotablePath = pathPrefix; - nonNotablePath += - (zStats.isTotals || anonymize) - ? NS_LITERAL_CSTRING("strings/") - : NS_LITERAL_CSTRING("strings/string()/"); + nonNotablePath += (zStats.isTotals || anonymize) + ? "strings/"_ns + : "strings/string()/"_ns; if (zStats.stringInfo.gcHeapLatin1 > 0) { - REPORT_GC_BYTES(nonNotablePath + NS_LITERAL_CSTRING("gc-heap/latin1"), + REPORT_GC_BYTES(nonNotablePath + "gc-heap/latin1"_ns, zStats.stringInfo.gcHeapLatin1, "Latin1 strings. " MAYBE_INLINE); } if (zStats.stringInfo.gcHeapTwoByte > 0) { - REPORT_GC_BYTES(nonNotablePath + NS_LITERAL_CSTRING("gc-heap/two-byte"), + REPORT_GC_BYTES(nonNotablePath + "gc-heap/two-byte"_ns, zStats.stringInfo.gcHeapTwoByte, "TwoByte strings. " MAYBE_INLINE); } if (zStats.stringInfo.mallocHeapLatin1 > 0) { - REPORT_BYTES(nonNotablePath + NS_LITERAL_CSTRING("malloc-heap/latin1"), - KIND_HEAP, zStats.stringInfo.mallocHeapLatin1, + REPORT_BYTES(nonNotablePath + "malloc-heap/latin1"_ns, KIND_HEAP, + zStats.stringInfo.mallocHeapLatin1, "Non-inline Latin1 string characters. " MAYBE_OVERALLOCATED); } if (zStats.stringInfo.mallocHeapTwoByte > 0) { - REPORT_BYTES(nonNotablePath + NS_LITERAL_CSTRING("malloc-heap/two-byte"), - KIND_HEAP, zStats.stringInfo.mallocHeapTwoByte, + REPORT_BYTES(nonNotablePath + "malloc-heap/two-byte"_ns, KIND_HEAP, + zStats.stringInfo.mallocHeapTwoByte, "Non-inline TwoByte string characters. " MAYBE_OVERALLOCATED); } if (stringsNotableAboutMemoryGCHeap > 0) { MOZ_ASSERT(!zStats.isTotals); REPORT_GC_BYTES( - pathPrefix + - NS_LITERAL_CSTRING("strings/string()/gc-heap"), + pathPrefix + "strings/string()/gc-heap"_ns, stringsNotableAboutMemoryGCHeap, "Strings that contain the characters '" STRING_LENGTH "', which " @@ -1584,9 +1570,8 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, if (stringsNotableAboutMemoryMallocHeap > 0) { MOZ_ASSERT(!zStats.isTotals); REPORT_BYTES( - pathPrefix + - NS_LITERAL_CSTRING("strings/string()/malloc-heap"), - KIND_HEAP, stringsNotableAboutMemoryMallocHeap, + pathPrefix + "strings/string()/malloc-heap"_ns, KIND_HEAP, + stringsNotableAboutMemoryMallocHeap, "Non-inline string characters of strings that contain the " "characters '" STRING_LENGTH "', which are probably from " @@ -1598,46 +1583,43 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, const JS::ShapeInfo& shapeInfo = zStats.shapeInfo; if (shapeInfo.shapesGCHeapTree > 0) { - REPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("shapes/gc-heap/tree"), + REPORT_GC_BYTES(pathPrefix + "shapes/gc-heap/tree"_ns, shapeInfo.shapesGCHeapTree, "Shapes in a property tree."); } if (shapeInfo.shapesGCHeapDict > 0) { - REPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("shapes/gc-heap/dict"), + REPORT_GC_BYTES(pathPrefix + "shapes/gc-heap/dict"_ns, shapeInfo.shapesGCHeapDict, "Shapes in dictionary mode."); } if (shapeInfo.shapesGCHeapBase > 0) { - REPORT_GC_BYTES(pathPrefix + NS_LITERAL_CSTRING("shapes/gc-heap/base"), + REPORT_GC_BYTES(pathPrefix + "shapes/gc-heap/base"_ns, shapeInfo.shapesGCHeapBase, "Base shapes, which collate data common to many shapes."); } if (shapeInfo.shapesMallocHeapTreeTables > 0) { - REPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("shapes/malloc-heap/tree-tables"), - KIND_HEAP, shapeInfo.shapesMallocHeapTreeTables, - "Property tables of shapes in a property tree."); + REPORT_BYTES(pathPrefix + "shapes/malloc-heap/tree-tables"_ns, KIND_HEAP, + shapeInfo.shapesMallocHeapTreeTables, + "Property tables of shapes in a property tree."); } if (shapeInfo.shapesMallocHeapDictTables > 0) { - REPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("shapes/malloc-heap/dict-tables"), - KIND_HEAP, shapeInfo.shapesMallocHeapDictTables, - "Property tables of shapes in dictionary mode."); + REPORT_BYTES(pathPrefix + "shapes/malloc-heap/dict-tables"_ns, KIND_HEAP, + shapeInfo.shapesMallocHeapDictTables, + "Property tables of shapes in dictionary mode."); } if (shapeInfo.shapesMallocHeapTreeChildren > 0) { - REPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("shapes/malloc-heap/tree-children"), - KIND_HEAP, shapeInfo.shapesMallocHeapTreeChildren, - "Sets of shape children in a property tree."); + REPORT_BYTES(pathPrefix + "shapes/malloc-heap/tree-children"_ns, KIND_HEAP, + shapeInfo.shapesMallocHeapTreeChildren, + "Sets of shape children in a property tree."); } if (sundriesGCHeap > 0) { // We deliberately don't use ZRREPORT_GC_BYTES here. REPORT_GC_BYTES( - pathPrefix + NS_LITERAL_CSTRING("sundries/gc-heap"), sundriesGCHeap, + pathPrefix + "sundries/gc-heap"_ns, sundriesGCHeap, "The sum of all 'gc-heap' measurements that are too small to be " "worth showing individually."); } @@ -1645,16 +1627,15 @@ static void ReportZoneStats(const JS::ZoneStats& zStats, if (sundriesMallocHeap > 0) { // We deliberately don't use ZRREPORT_BYTES here. REPORT_BYTES( - pathPrefix + NS_LITERAL_CSTRING("sundries/malloc-heap"), KIND_HEAP, - sundriesMallocHeap, + pathPrefix + "sundries/malloc-heap"_ns, KIND_HEAP, sundriesMallocHeap, "The sum of all 'malloc-heap' measurements that are too small to " "be worth showing individually."); } if (sundriesNonHeap > 0) { // We deliberately don't use ZRREPORT_NONHEAP_BYTES here. - REPORT_BYTES(pathPrefix + NS_LITERAL_CSTRING("sundries/other-heap"), - KIND_NONHEAP, sundriesNonHeap, + REPORT_BYTES(pathPrefix + "sundries/other-heap"_ns, KIND_NONHEAP, + sundriesNonHeap, "The sum of non-malloc/gc measurements that are too small to " "be worth showing individually."); } @@ -1673,46 +1654,42 @@ static void ReportClassStats(const ClassInfo& classInfo, const nsACString& path, // don't go into sundries. if (classInfo.objectsGCHeap > 0) { - REPORT_GC_BYTES(path + NS_LITERAL_CSTRING("objects/gc-heap"), - classInfo.objectsGCHeap, "Objects, including fixed slots."); + REPORT_GC_BYTES(path + "objects/gc-heap"_ns, classInfo.objectsGCHeap, + "Objects, including fixed slots."); } if (classInfo.objectsMallocHeapSlots > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("objects/malloc-heap/slots"), - KIND_HEAP, classInfo.objectsMallocHeapSlots, - "Non-fixed object slots."); + REPORT_BYTES(path + "objects/malloc-heap/slots"_ns, KIND_HEAP, + classInfo.objectsMallocHeapSlots, "Non-fixed object slots."); } if (classInfo.objectsMallocHeapElementsNormal > 0) { - REPORT_BYTES( - path + NS_LITERAL_CSTRING("objects/malloc-heap/elements/normal"), - KIND_HEAP, classInfo.objectsMallocHeapElementsNormal, - "Normal (non-wasm) indexed elements."); + REPORT_BYTES(path + "objects/malloc-heap/elements/normal"_ns, KIND_HEAP, + classInfo.objectsMallocHeapElementsNormal, + "Normal (non-wasm) indexed elements."); } if (classInfo.objectsMallocHeapElementsAsmJS > 0) { - REPORT_BYTES( - path + NS_LITERAL_CSTRING("objects/malloc-heap/elements/asm.js"), - KIND_HEAP, classInfo.objectsMallocHeapElementsAsmJS, - "asm.js array buffer elements allocated in the malloc heap."); + REPORT_BYTES(path + "objects/malloc-heap/elements/asm.js"_ns, KIND_HEAP, + classInfo.objectsMallocHeapElementsAsmJS, + "asm.js array buffer elements allocated in the malloc heap."); } if (classInfo.objectsMallocHeapMisc > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("objects/malloc-heap/misc"), - KIND_HEAP, classInfo.objectsMallocHeapMisc, - "Miscellaneous object data."); + REPORT_BYTES(path + "objects/malloc-heap/misc"_ns, KIND_HEAP, + classInfo.objectsMallocHeapMisc, "Miscellaneous object data."); } if (classInfo.objectsNonHeapElementsNormal > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("objects/non-heap/elements/normal"), - KIND_NONHEAP, classInfo.objectsNonHeapElementsNormal, + REPORT_BYTES(path + "objects/non-heap/elements/normal"_ns, KIND_NONHEAP, + classInfo.objectsNonHeapElementsNormal, "Memory-mapped non-shared array buffer elements."); } if (classInfo.objectsNonHeapElementsShared > 0) { REPORT_BYTES( - path + NS_LITERAL_CSTRING("objects/non-heap/elements/shared"), - KIND_NONHEAP, classInfo.objectsNonHeapElementsShared, + path + "objects/non-heap/elements/shared"_ns, KIND_NONHEAP, + classInfo.objectsNonHeapElementsShared, "Memory-mapped shared array buffer elements. These elements are " "shared between one or more runtimes; the reported size is divided " "by the buffer's refcount."); @@ -1723,15 +1700,15 @@ static void ReportClassStats(const ClassInfo& classInfo, const nsACString& path, // larger than the sundries threshold, and (b) we'd need a third category of // sundries ("non-heap"), which would be a pain. if (classInfo.objectsNonHeapElementsWasm > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("objects/non-heap/elements/wasm"), - KIND_NONHEAP, classInfo.objectsNonHeapElementsWasm, + REPORT_BYTES(path + "objects/non-heap/elements/wasm"_ns, KIND_NONHEAP, + classInfo.objectsNonHeapElementsWasm, "wasm/asm.js array buffer elements allocated outside both the " "malloc heap and the GC heap."); } if (classInfo.objectsNonHeapCodeWasm > 0) { - REPORT_BYTES(path + NS_LITERAL_CSTRING("objects/non-heap/code/wasm"), - KIND_NONHEAP, classInfo.objectsNonHeapCodeWasm, + REPORT_BYTES(path + "objects/non-heap/code/wasm"_ns, KIND_NONHEAP, + classInfo.objectsNonHeapCodeWasm, "AOT-compiled wasm/asm.js code."); } @@ -1739,8 +1716,7 @@ static void ReportClassStats(const ClassInfo& classInfo, const nsACString& path, // large and contribute greatly to vsize and so are worth reporting. if (classInfo.wasmGuardPages > 0) { REPORT_BYTES( - NS_LITERAL_CSTRING("wasm-guard-pages"), KIND_OTHER, - classInfo.wasmGuardPages, + "wasm-guard-pages"_ns, KIND_OTHER, classInfo.wasmGuardPages, "Guard pages mapped after the end of wasm memories, reserved for " "optimization tricks, but not committed and thus never contributing" " to RSS, only vsize."); @@ -1760,10 +1736,9 @@ static void ReportRealmStats(const JS::RealmStats& realmStats, MOZ_ASSERT(!gcTotalOut == realmStats.isTotals); nsCString nonNotablePath = realmJSPathPrefix; - nonNotablePath += - realmStats.isTotals - ? NS_LITERAL_CSTRING("classes/") - : NS_LITERAL_CSTRING("classes/class()/"); + nonNotablePath += realmStats.isTotals + ? "classes/"_ns + : "classes/class()/"_ns; ReportClassStats(realmStats.classInfo, nonNotablePath, handleReport, data, gcTotal); @@ -1783,88 +1758,74 @@ static void ReportRealmStats(const JS::RealmStats& realmStats, // orphan DOM nodes in the JS reporter, but we want to report them in a "dom" // sub-tree rather than a "js" sub-tree. ZRREPORT_BYTES( - realmDOMPathPrefix + NS_LITERAL_CSTRING("orphan-nodes"), - realmStats.objectsPrivate, + realmDOMPathPrefix + "orphan-nodes"_ns, realmStats.objectsPrivate, "Orphan DOM nodes, i.e. those that are only reachable from JavaScript " "objects."); ZRREPORT_GC_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("scripts/gc-heap"), - realmStats.scriptsGCHeap, + realmJSPathPrefix + "scripts/gc-heap"_ns, realmStats.scriptsGCHeap, "JSScript instances. There is one per user-defined function in a " "script, and one for the top-level code in a script."); - ZRREPORT_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("scripts/malloc-heap/data"), - realmStats.scriptsMallocHeapData, - "Various variable-length tables in JSScripts."); + ZRREPORT_BYTES(realmJSPathPrefix + "scripts/malloc-heap/data"_ns, + realmStats.scriptsMallocHeapData, + "Various variable-length tables in JSScripts."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("baseline/data"), + ZRREPORT_BYTES(realmJSPathPrefix + "baseline/data"_ns, realmStats.baselineData, "The Baseline JIT's compilation data (BaselineScripts)."); - ZRREPORT_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("baseline/fallback-stubs"), - realmStats.baselineStubsFallback, - "The Baseline JIT's fallback IC stubs (excluding code)."); + ZRREPORT_BYTES(realmJSPathPrefix + "baseline/fallback-stubs"_ns, + realmStats.baselineStubsFallback, + "The Baseline JIT's fallback IC stubs (excluding code)."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("ion-data"), - realmStats.ionData, + ZRREPORT_BYTES(realmJSPathPrefix + "ion-data"_ns, realmStats.ionData, "The IonMonkey JIT's compilation data (IonScripts)."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("jit-scripts"), - realmStats.jitScripts, + ZRREPORT_BYTES(realmJSPathPrefix + "jit-scripts"_ns, realmStats.jitScripts, "JIT and Type Inference data associated with scripts."); - ZRREPORT_BYTES( - realmJSPathPrefix + - NS_LITERAL_CSTRING("type-inference/allocation-site-tables"), - realmStats.typeInferenceAllocationSiteTables, - "Tables of type objects associated with allocation sites."); + ZRREPORT_BYTES(realmJSPathPrefix + "type-inference/allocation-site-tables"_ns, + realmStats.typeInferenceAllocationSiteTables, + "Tables of type objects associated with allocation sites."); - ZRREPORT_BYTES(realmJSPathPrefix + - NS_LITERAL_CSTRING("type-inference/array-type-tables"), + ZRREPORT_BYTES(realmJSPathPrefix + "type-inference/array-type-tables"_ns, realmStats.typeInferenceArrayTypeTables, "Tables of type objects associated with array literals."); - ZRREPORT_BYTES(realmJSPathPrefix + - NS_LITERAL_CSTRING("type-inference/object-type-tables"), + ZRREPORT_BYTES(realmJSPathPrefix + "type-inference/object-type-tables"_ns, realmStats.typeInferenceObjectTypeTables, "Tables of type objects associated with object literals."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("realm-object"), - realmStats.realmObject, "The JS::Realm object itself."); + ZRREPORT_BYTES(realmJSPathPrefix + "realm-object"_ns, realmStats.realmObject, + "The JS::Realm object itself."); ZRREPORT_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("realm-tables"), - realmStats.realmTables, + realmJSPathPrefix + "realm-tables"_ns, realmStats.realmTables, "Realm-wide tables storing object group information and wasm instances."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("inner-views"), + ZRREPORT_BYTES(realmJSPathPrefix + "inner-views"_ns, realmStats.innerViewsTable, "The table for array buffer inner views."); ZRREPORT_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("object-metadata"), - realmStats.objectMetadataTable, + realmJSPathPrefix + "object-metadata"_ns, realmStats.objectMetadataTable, "The table used by debugging tools for tracking object metadata"); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("saved-stacks-set"), + ZRREPORT_BYTES(realmJSPathPrefix + "saved-stacks-set"_ns, realmStats.savedStacksSet, "The saved stacks set."); - ZRREPORT_BYTES(realmJSPathPrefix + - NS_LITERAL_CSTRING("non-syntactic-lexical-scopes-table"), + ZRREPORT_BYTES(realmJSPathPrefix + "non-syntactic-lexical-scopes-table"_ns, realmStats.nonSyntacticLexicalScopesTable, "The non-syntactic lexical scopes table."); - ZRREPORT_BYTES(realmJSPathPrefix + NS_LITERAL_CSTRING("jit-realm"), - realmStats.jitRealm, "The JIT realm."); + ZRREPORT_BYTES(realmJSPathPrefix + "jit-realm"_ns, realmStats.jitRealm, + "The JIT realm."); if (sundriesGCHeap > 0) { // We deliberately don't use ZRREPORT_GC_BYTES here. REPORT_GC_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("sundries/gc-heap"), - sundriesGCHeap, + realmJSPathPrefix + "sundries/gc-heap"_ns, sundriesGCHeap, "The sum of all 'gc-heap' measurements that are too small to be " "worth showing individually."); } @@ -1872,8 +1833,8 @@ static void ReportRealmStats(const JS::RealmStats& realmStats, if (sundriesMallocHeap > 0) { // We deliberately don't use ZRREPORT_BYTES here. REPORT_BYTES( - realmJSPathPrefix + NS_LITERAL_CSTRING("sundries/malloc-heap"), - KIND_HEAP, sundriesMallocHeap, + realmJSPathPrefix + "sundries/malloc-heap"_ns, KIND_HEAP, + sundriesMallocHeap, "The sum of all 'malloc-heap' measurements that are too small to " "be worth showing individually."); } @@ -1888,8 +1849,7 @@ static void ReportScriptSourceStats(const ScriptSourceInfo& scriptSourceInfo, nsIHandleReportCallback* handleReport, nsISupports* data, size_t& rtTotal) { if (scriptSourceInfo.misc > 0) { - RREPORT_BYTES(path + NS_LITERAL_CSTRING("misc"), KIND_HEAP, - scriptSourceInfo.misc, + RREPORT_BYTES(path + "misc"_ns, KIND_HEAP, scriptSourceInfo.misc, "Miscellaneous data relating to JavaScript source code."); } } @@ -1921,50 +1881,47 @@ void ReportJSRuntimeExplicitTreeStats(const JS::RuntimeStats& rtStats, size_t rtTotal = 0; - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/runtime-object"), - KIND_HEAP, rtStats.runtime.object, "The JSRuntime object."); + RREPORT_BYTES(rtPath + "runtime/runtime-object"_ns, KIND_HEAP, + rtStats.runtime.object, "The JSRuntime object."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/atoms-table"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/atoms-table"_ns, KIND_HEAP, rtStats.runtime.atomsTable, "The atoms table."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/atoms-mark-bitmaps"), - KIND_HEAP, rtStats.runtime.atomsMarkBitmaps, + RREPORT_BYTES(rtPath + "runtime/atoms-mark-bitmaps"_ns, KIND_HEAP, + rtStats.runtime.atomsMarkBitmaps, "Mark bitmaps for atoms held by each zone."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/contexts"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/contexts"_ns, KIND_HEAP, rtStats.runtime.contexts, "JSContext objects and structures that belong to them."); RREPORT_BYTES( - rtPath + NS_LITERAL_CSTRING("runtime/temporary"), KIND_HEAP, - rtStats.runtime.temporary, + rtPath + "runtime/temporary"_ns, KIND_HEAP, rtStats.runtime.temporary, "Transient data (mostly parse nodes) held by the JSRuntime during " "compilation."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/interpreter-stack"), - KIND_HEAP, rtStats.runtime.interpreterStack, - "JS interpreter frames."); + RREPORT_BYTES(rtPath + "runtime/interpreter-stack"_ns, KIND_HEAP, + rtStats.runtime.interpreterStack, "JS interpreter frames."); RREPORT_BYTES( - rtPath + NS_LITERAL_CSTRING("runtime/shared-immutable-strings-cache"), - KIND_HEAP, rtStats.runtime.sharedImmutableStringsCache, + rtPath + "runtime/shared-immutable-strings-cache"_ns, KIND_HEAP, + rtStats.runtime.sharedImmutableStringsCache, "Immutable strings (such as JS scripts' source text) shared across all " "JSRuntimes."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/shared-intl-data"), - KIND_HEAP, rtStats.runtime.sharedIntlData, + RREPORT_BYTES(rtPath + "runtime/shared-intl-data"_ns, KIND_HEAP, + rtStats.runtime.sharedIntlData, "Shared internationalization data."); - RREPORT_BYTES( - rtPath + NS_LITERAL_CSTRING("runtime/uncompressed-source-cache"), - KIND_HEAP, rtStats.runtime.uncompressedSourceCache, - "The uncompressed source code cache."); + RREPORT_BYTES(rtPath + "runtime/uncompressed-source-cache"_ns, KIND_HEAP, + rtStats.runtime.uncompressedSourceCache, + "The uncompressed source code cache."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/script-data"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/script-data"_ns, KIND_HEAP, rtStats.runtime.scriptData, "The table holding script data shared in the runtime."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/tracelogger"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/tracelogger"_ns, KIND_HEAP, rtStats.runtime.tracelogger, "The memory used for the tracelogger (per-runtime)."); @@ -2004,40 +1961,39 @@ void ReportJSRuntimeExplicitTreeStats(const JS::RuntimeStats& rtStats, rtTotal); } - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/marker"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/gc/marker"_ns, KIND_HEAP, rtStats.runtime.gc.marker, "The GC mark stack and gray roots."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/nursery-committed"), - KIND_NONHEAP, rtStats.runtime.gc.nurseryCommitted, + RREPORT_BYTES(rtPath + "runtime/gc/nursery-committed"_ns, KIND_NONHEAP, + rtStats.runtime.gc.nurseryCommitted, "Memory being used by the GC's nursery."); RREPORT_BYTES( - rtPath + NS_LITERAL_CSTRING("runtime/gc/nursery-malloced-buffers"), - KIND_HEAP, rtStats.runtime.gc.nurseryMallocedBuffers, + rtPath + "runtime/gc/nursery-malloced-buffers"_ns, KIND_HEAP, + rtStats.runtime.gc.nurseryMallocedBuffers, "Out-of-line slots and elements belonging to objects in the nursery."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/store-buffer/vals"), - KIND_HEAP, rtStats.runtime.gc.storeBufferVals, + RREPORT_BYTES(rtPath + "runtime/gc/store-buffer/vals"_ns, KIND_HEAP, + rtStats.runtime.gc.storeBufferVals, "Values in the store buffer."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/store-buffer/cells"), - KIND_HEAP, rtStats.runtime.gc.storeBufferCells, + RREPORT_BYTES(rtPath + "runtime/gc/store-buffer/cells"_ns, KIND_HEAP, + rtStats.runtime.gc.storeBufferCells, "Cells in the store buffer."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/store-buffer/slots"), - KIND_HEAP, rtStats.runtime.gc.storeBufferSlots, + RREPORT_BYTES(rtPath + "runtime/gc/store-buffer/slots"_ns, KIND_HEAP, + rtStats.runtime.gc.storeBufferSlots, "Slots in the store buffer."); - RREPORT_BYTES( - rtPath + NS_LITERAL_CSTRING("runtime/gc/store-buffer/whole-cells"), - KIND_HEAP, rtStats.runtime.gc.storeBufferWholeCells, - "Whole cells in the store buffer."); + RREPORT_BYTES(rtPath + "runtime/gc/store-buffer/whole-cells"_ns, KIND_HEAP, + rtStats.runtime.gc.storeBufferWholeCells, + "Whole cells in the store buffer."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/gc/store-buffer/generics"), - KIND_HEAP, rtStats.runtime.gc.storeBufferGenerics, + RREPORT_BYTES(rtPath + "runtime/gc/store-buffer/generics"_ns, KIND_HEAP, + rtStats.runtime.gc.storeBufferGenerics, "Generic things in the store buffer."); - RREPORT_BYTES(rtPath + NS_LITERAL_CSTRING("runtime/jit-lazylink"), KIND_HEAP, + RREPORT_BYTES(rtPath + "runtime/jit-lazylink"_ns, KIND_HEAP, rtStats.runtime.jitLazyLink, "IonMonkey compilations waiting for lazy linking."); @@ -2053,23 +2009,21 @@ void ReportJSRuntimeExplicitTreeStats(const JS::RuntimeStats& rtStats, rtPath2.ReplaceLiteral(0, strlen("explicit"), "decommitted"); REPORT_GC_BYTES( - rtPath2 + NS_LITERAL_CSTRING("gc-heap/decommitted-arenas"), + rtPath2 + "gc-heap/decommitted-arenas"_ns, rtStats.gcHeapDecommittedArenas, "GC arenas in non-empty chunks that is decommitted, i.e. it takes up " "address space but no physical memory or swap space."); REPORT_GC_BYTES( - rtPath + NS_LITERAL_CSTRING("gc-heap/unused-chunks"), - rtStats.gcHeapUnusedChunks, + rtPath + "gc-heap/unused-chunks"_ns, rtStats.gcHeapUnusedChunks, "Empty GC chunks which will soon be released unless claimed for new " "allocations."); - REPORT_GC_BYTES(rtPath + NS_LITERAL_CSTRING("gc-heap/unused-arenas"), + REPORT_GC_BYTES(rtPath + "gc-heap/unused-arenas"_ns, rtStats.gcHeapUnusedArenas, "Empty GC arenas within non-empty chunks."); - REPORT_GC_BYTES(rtPath + NS_LITERAL_CSTRING("gc-heap/chunk-admin"), - rtStats.gcHeapChunkAdmin, + REPORT_GC_BYTES(rtPath + "gc-heap/chunk-admin"_ns, rtStats.gcHeapChunkAdmin, "Bookkeeping information within GC chunks."); // gcTotal is the sum of everything we've reported for the GC heap. It @@ -2095,9 +2049,8 @@ class JSMainRuntimeRealmsReporter final : public nsIMemoryReporter { Data* data = static_cast(vdata); nsCString path; GetRealmName(realm, path, &data->anonymizeID, /* replaceSlashes = */ true); - path.Insert(js::IsSystemRealm(realm) - ? NS_LITERAL_CSTRING("js-main-runtime-realms/system/") - : NS_LITERAL_CSTRING("js-main-runtime-realms/user/"), + path.Insert(js::IsSystemRealm(realm) ? "js-main-runtime-realms/system/"_ns + : "js-main-runtime-realms/user/"_ns, 0); mozilla::Unused << data->paths.append(path); } @@ -2167,7 +2120,7 @@ class OrphanReporter : public JS::ObjectPrivateVisitor { #ifdef DEBUG static bool StartsWithExplicit(nsACString& s) { - return StringBeginsWith(s, NS_LITERAL_CSTRING("explicit/")); + return StringBeginsWith(s, "explicit/"_ns); } #endif @@ -2260,8 +2213,7 @@ class XPCJSRuntimeStats : public JS::RuntimeStats { nsPrintfCString("zone(0x%p)/", (void*)js::GetRealmZone(realm)); } - extras->jsPathPrefix += - NS_LITERAL_CSTRING("realm(") + rName + NS_LITERAL_CSTRING(")/"); + extras->jsPathPrefix += "realm("_ns + rName + ")/"_ns; // extras->jsPathPrefix is used for almost all the realm-specific // reports. At this point it has the form @@ -2325,9 +2277,9 @@ void JSReporter::CollectReports(WindowPaths* windowPaths, // "explicit" tree, then we report other stuff. size_t rtTotal = 0; - xpc::ReportJSRuntimeExplicitTreeStats( - rtStats, NS_LITERAL_CSTRING("explicit/js-non-window/"), handleReport, - data, anonymize, &rtTotal); + xpc::ReportJSRuntimeExplicitTreeStats(rtStats, "explicit/js-non-window/"_ns, + handleReport, data, anonymize, + &rtTotal); // Report the sums of the realm numbers. xpc::RealmStatsExtras realmExtrasTotal; @@ -2341,138 +2293,133 @@ void JSReporter::CollectReports(WindowPaths* windowPaths, // Report the sum of the runtime/ numbers. REPORT_BYTES( - NS_LITERAL_CSTRING("js-main-runtime/runtime"), KIND_OTHER, rtTotal, + "js-main-runtime/runtime"_ns, KIND_OTHER, rtTotal, "The sum of all measurements under 'explicit/js-non-window/runtime/'."); // Report the number of HelperThread - REPORT(NS_LITERAL_CSTRING("js-helper-threads/idle"), KIND_OTHER, UNITS_COUNT, + REPORT("js-helper-threads/idle"_ns, KIND_OTHER, UNITS_COUNT, gStats.helperThread.idleThreadCount, "The current number of idle JS HelperThreads."); REPORT( - NS_LITERAL_CSTRING("js-helper-threads/active"), KIND_OTHER, UNITS_COUNT, + "js-helper-threads/active"_ns, KIND_OTHER, UNITS_COUNT, gStats.helperThread.activeThreadCount, "The current number of active JS HelperThreads. Memory held by these is" " not reported."); // Report the numbers for memory used by wasm Runtime state. - REPORT_BYTES(NS_LITERAL_CSTRING("wasm-runtime"), KIND_OTHER, - rtStats.runtime.wasmRuntime, + REPORT_BYTES("wasm-runtime"_ns, KIND_OTHER, rtStats.runtime.wasmRuntime, "The memory used for wasm runtime bookkeeping."); // Report the numbers for memory outside of realms. - REPORT_BYTES(NS_LITERAL_CSTRING("js-main-runtime/gc-heap/unused-chunks"), - KIND_OTHER, rtStats.gcHeapUnusedChunks, + REPORT_BYTES("js-main-runtime/gc-heap/unused-chunks"_ns, KIND_OTHER, + rtStats.gcHeapUnusedChunks, "The same as 'explicit/js-non-window/gc-heap/unused-chunks'."); - REPORT_BYTES(NS_LITERAL_CSTRING("js-main-runtime/gc-heap/unused-arenas"), - KIND_OTHER, rtStats.gcHeapUnusedArenas, + REPORT_BYTES("js-main-runtime/gc-heap/unused-arenas"_ns, KIND_OTHER, + rtStats.gcHeapUnusedArenas, "The same as 'explicit/js-non-window/gc-heap/unused-arenas'."); - REPORT_BYTES(NS_LITERAL_CSTRING("js-main-runtime/gc-heap/chunk-admin"), - KIND_OTHER, rtStats.gcHeapChunkAdmin, + REPORT_BYTES("js-main-runtime/gc-heap/chunk-admin"_ns, KIND_OTHER, + rtStats.gcHeapChunkAdmin, "The same as 'explicit/js-non-window/gc-heap/chunk-admin'."); // Report a breakdown of the committed GC space. - REPORT_BYTES( - NS_LITERAL_CSTRING("js-main-runtime-gc-heap-committed/unused/chunks"), - KIND_OTHER, rtStats.gcHeapUnusedChunks, - "The same as 'explicit/js-non-window/gc-heap/unused-chunks'."); + REPORT_BYTES("js-main-runtime-gc-heap-committed/unused/chunks"_ns, KIND_OTHER, + rtStats.gcHeapUnusedChunks, + "The same as 'explicit/js-non-window/gc-heap/unused-chunks'."); - REPORT_BYTES( - NS_LITERAL_CSTRING("js-main-runtime-gc-heap-committed/unused/arenas"), - KIND_OTHER, rtStats.gcHeapUnusedArenas, - "The same as 'explicit/js-non-window/gc-heap/unused-arenas'."); + REPORT_BYTES("js-main-runtime-gc-heap-committed/unused/arenas"_ns, KIND_OTHER, + rtStats.gcHeapUnusedArenas, + "The same as 'explicit/js-non-window/gc-heap/unused-arenas'."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/objects"), KIND_OTHER, rtStats.zTotals.unusedGCThings.object, "Unused object cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/strings"), KIND_OTHER, rtStats.zTotals.unusedGCThings.string, "Unused string cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/symbols"), KIND_OTHER, rtStats.zTotals.unusedGCThings.symbol, "Unused symbol cells within non-empty arenas."); - REPORT_BYTES(NS_LITERAL_CSTRING( + REPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/shapes"), KIND_OTHER, rtStats.zTotals.unusedGCThings.shape, "Unused shape cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/base-shapes"), KIND_OTHER, rtStats.zTotals.unusedGCThings.baseShape, "Unused base shape cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/object-groups"), KIND_OTHER, rtStats.zTotals.unusedGCThings.objectGroup, "Unused object group cells within non-empty arenas."); - REPORT_BYTES(NS_LITERAL_CSTRING( + REPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/scopes"), KIND_OTHER, rtStats.zTotals.unusedGCThings.scope, "Unused scope cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/scripts"), KIND_OTHER, rtStats.zTotals.unusedGCThings.script, "Unused script cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/jitcode"), KIND_OTHER, rtStats.zTotals.unusedGCThings.jitcode, "Unused jitcode cells within non-empty arenas."); REPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/unused/gc-things/regexp-shareds"), KIND_OTHER, rtStats.zTotals.unusedGCThings.regExpShared, "Unused regexpshared cells within non-empty arenas."); - REPORT_BYTES( - NS_LITERAL_CSTRING("js-main-runtime-gc-heap-committed/used/chunk-admin"), - KIND_OTHER, rtStats.gcHeapChunkAdmin, - "The same as 'explicit/js-non-window/gc-heap/chunk-admin'."); + REPORT_BYTES("js-main-runtime-gc-heap-committed/used/chunk-admin"_ns, + KIND_OTHER, rtStats.gcHeapChunkAdmin, + "The same as 'explicit/js-non-window/gc-heap/chunk-admin'."); - REPORT_BYTES( - NS_LITERAL_CSTRING("js-main-runtime-gc-heap-committed/used/arena-admin"), - KIND_OTHER, rtStats.zTotals.gcHeapArenaAdmin, - "The same as 'js-main-runtime/zones/gc-heap-arena-admin'."); + REPORT_BYTES("js-main-runtime-gc-heap-committed/used/arena-admin"_ns, + KIND_OTHER, rtStats.zTotals.gcHeapArenaAdmin, + "The same as 'js-main-runtime/zones/gc-heap-arena-admin'."); size_t gcThingTotal = 0; - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/objects"), KIND_OTHER, rtStats.realmTotals.classInfo.objectsGCHeap, "Used object cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/strings"), KIND_OTHER, rtStats.zTotals.stringInfo.sizeOfLiveGCThings(), "Used string cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/symbols"), KIND_OTHER, rtStats.zTotals.symbolsGCHeap, "Used symbol cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/shapes"), KIND_OTHER, rtStats.zTotals.shapeInfo.shapesGCHeapTree + @@ -2480,33 +2427,33 @@ void JSReporter::CollectReports(WindowPaths* windowPaths, "Used shape cells."); MREPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/base-shapes"), KIND_OTHER, rtStats.zTotals.shapeInfo.shapesGCHeapBase, "Used base shape cells."); MREPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/object-groups"), KIND_OTHER, rtStats.zTotals.objectGroupsGCHeap, "Used object group cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/scopes"), KIND_OTHER, rtStats.zTotals.scopesGCHeap, "Used scope cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/scripts"), KIND_OTHER, rtStats.realmTotals.scriptsGCHeap, "Used script cells."); - MREPORT_BYTES(NS_LITERAL_CSTRING( + MREPORT_BYTES(nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/jitcode"), KIND_OTHER, rtStats.zTotals.jitCodesGCHeap, "Used jitcode cells."); MREPORT_BYTES( - NS_LITERAL_CSTRING( + nsLiteralCString( "js-main-runtime-gc-heap-committed/used/gc-things/regexp-shareds"), KIND_OTHER, rtStats.zTotals.regExpSharedsGCHeap, "Used regexpshared cells."); @@ -2515,58 +2462,51 @@ void JSReporter::CollectReports(WindowPaths* windowPaths, // Report xpconnect. - REPORT_BYTES(NS_LITERAL_CSTRING("explicit/xpconnect/runtime"), KIND_HEAP, - xpcJSRuntimeSize, "The XPConnect runtime."); + REPORT_BYTES("explicit/xpconnect/runtime"_ns, KIND_HEAP, xpcJSRuntimeSize, + "The XPConnect runtime."); - REPORT_BYTES(NS_LITERAL_CSTRING("explicit/xpconnect/wrappedjs"), KIND_HEAP, - wrappedJSSize, + REPORT_BYTES("explicit/xpconnect/wrappedjs"_ns, KIND_HEAP, wrappedJSSize, "Wrappers used to implement XPIDL interfaces with JS."); - REPORT_BYTES(NS_LITERAL_CSTRING("explicit/xpconnect/scopes"), KIND_HEAP, + REPORT_BYTES("explicit/xpconnect/scopes"_ns, KIND_HEAP, sizeInfo.mScopeAndMapSize, "XPConnect scopes."); - REPORT_BYTES(NS_LITERAL_CSTRING("explicit/xpconnect/proto-iface-cache"), - KIND_HEAP, sizeInfo.mProtoAndIfaceCacheSize, + REPORT_BYTES("explicit/xpconnect/proto-iface-cache"_ns, KIND_HEAP, + sizeInfo.mProtoAndIfaceCacheSize, "Prototype and interface binding caches."); - REPORT_BYTES(NS_LITERAL_CSTRING("explicit/xpconnect/js-component-loader"), - KIND_HEAP, jsComponentLoaderSize, - "XPConnect's JS component loader."); + REPORT_BYTES("explicit/xpconnect/js-component-loader"_ns, KIND_HEAP, + jsComponentLoaderSize, "XPConnect's JS component loader."); // Report tracelogger (global). REPORT_BYTES( - NS_LITERAL_CSTRING("explicit/js-non-window/tracelogger"), KIND_HEAP, - gStats.tracelogger, + "explicit/js-non-window/tracelogger"_ns, KIND_HEAP, gStats.tracelogger, "The memory used for the tracelogger, including the graph and events."); // Report HelperThreadState. - REPORT_BYTES( - NS_LITERAL_CSTRING("explicit/js-non-window/helper-thread/heap-other"), - KIND_HEAP, gStats.helperThread.stateData, - "Memory used by HelperThreadState."); + REPORT_BYTES("explicit/js-non-window/helper-thread/heap-other"_ns, KIND_HEAP, + gStats.helperThread.stateData, + "Memory used by HelperThreadState."); - REPORT_BYTES( - NS_LITERAL_CSTRING("explicit/js-non-window/helper-thread/parse-task"), - KIND_HEAP, gStats.helperThread.parseTask, - "The memory used by ParseTasks waiting in HelperThreadState."); + REPORT_BYTES("explicit/js-non-window/helper-thread/parse-task"_ns, KIND_HEAP, + gStats.helperThread.parseTask, + "The memory used by ParseTasks waiting in HelperThreadState."); REPORT_BYTES( - NS_LITERAL_CSTRING( - "explicit/js-non-window/helper-thread/ion-compile-task"), - KIND_HEAP, gStats.helperThread.ionCompileTask, + "explicit/js-non-window/helper-thread/ion-compile-task"_ns, KIND_HEAP, + gStats.helperThread.ionCompileTask, "The memory used by IonCompileTasks waiting in HelperThreadState."); REPORT_BYTES( - NS_LITERAL_CSTRING("explicit/js-non-window/helper-thread/wasm-compile"), - KIND_HEAP, gStats.helperThread.wasmCompile, + "explicit/js-non-window/helper-thread/wasm-compile"_ns, KIND_HEAP, + gStats.helperThread.wasmCompile, "The memory used by Wasm compilations waiting in HelperThreadState."); - REPORT_BYTES( - NS_LITERAL_CSTRING("explicit/js-non-window/helper-thread/contexts"), - KIND_HEAP, gStats.helperThread.contexts, - "The memory used by the JSContexts in HelperThreadState."); + REPORT_BYTES("explicit/js-non-window/helper-thread/contexts"_ns, KIND_HEAP, + gStats.helperThread.contexts, + "The memory used by the JSContexts in HelperThreadState."); } static nsresult JSSizeOfTab(JSObject* objArg, size_t* jsObjectsSize, @@ -2814,7 +2754,7 @@ static nsresult ReadSourceFromFilename(JSContext* cx, const char* filename, // Explicitly set the content type so that we don't load the // exthandler to guess it. - scriptChannel->SetContentType(NS_LITERAL_CSTRING("text/plain")); + scriptChannel->SetContentType("text/plain"_ns); nsCOMPtr scriptStream; rv = scriptChannel->Open(getter_AddRefs(scriptStream)); @@ -2866,7 +2806,7 @@ static nsresult ReadSourceFromFilename(JSContext* cx, const char* filename, // On success this overwrites |*twoByteSource| and |*len|. rv = ScriptLoader::ConvertToUTF16( scriptChannel, reinterpret_cast(buf.get()), - rawLen, NS_LITERAL_STRING("UTF-8"), nullptr, *twoByteSource, *len); + rawLen, u"UTF-8"_ns, nullptr, *twoByteSource, *len); NS_ENSURE_SUCCESS(rv, rv); if (!*twoByteSource) { @@ -3368,7 +3308,7 @@ nsresult HelperThreadPool::Dispatch( HelperThreadPool::HelperThreadPool() { mPool = new nsThreadPool(); - mPool->SetName(NS_LITERAL_CSTRING("JSHelperThreads")); + mPool->SetName("JSHelperThreads"_ns); mPool->SetThreadLimit(GetAndClampCPUCount()); // Helper threads need a larger stack size than the default nsThreadPool stack // size. These values are described in detail in HelperThreads.cpp. diff --git a/js/xpconnect/src/XPCShellImpl.cpp b/js/xpconnect/src/XPCShellImpl.cpp index 12ed1f6e2c7c..ba49ca43c9c9 100644 --- a/js/xpconnect/src/XPCShellImpl.cpp +++ b/js/xpconnect/src/XPCShellImpl.cpp @@ -1116,7 +1116,7 @@ int XRE_XPCShellMain(int argc, char** argv, char** envp, XRE_GetFileFromPath(argv[0], getter_AddRefs(greDir)); greDir->GetParent(getter_AddRefs(tmpDir)); tmpDir->Clone(getter_AddRefs(greDir)); - tmpDir->SetNativeLeafName(NS_LITERAL_CSTRING("Resources")); + tmpDir->SetNativeLeafName("Resources"_ns); bool dirExists = false; tmpDir->Exists(&dirExists); if (dirExists) { @@ -1402,7 +1402,7 @@ void XPCShellDirProvider::SetGREDirs(nsIFile* greDir) { nsAutoCString leafName; mGREDir->GetNativeLeafName(leafName); if (leafName.EqualsLiteral("Resources")) { - mGREBinDir->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS")); + mGREBinDir->SetNativeLeafName("MacOS"_ns); } #endif } @@ -1440,8 +1440,8 @@ XPCShellDirProvider::GetFile(const char* prop, bool* persistent, nsCOMPtr file; *persistent = true; if (NS_FAILED(mGREDir->Clone(getter_AddRefs(file))) || - NS_FAILED(file->AppendNative(NS_LITERAL_CSTRING("defaults"))) || - NS_FAILED(file->AppendNative(NS_LITERAL_CSTRING("pref")))) + NS_FAILED(file->AppendNative("defaults"_ns)) || + NS_FAILED(file->AppendNative("pref"_ns))) return NS_ERROR_FAILURE; file.forget(result); return NS_OK; @@ -1457,7 +1457,7 @@ XPCShellDirProvider::GetFiles(const char* prop, nsISimpleEnumerator** result) { nsCOMPtr file; mGREDir->Clone(getter_AddRefs(file)); - file->AppendNative(NS_LITERAL_CSTRING("chrome")); + file->AppendNative("chrome"_ns); dirs.AppendObject(file); nsresult rv = @@ -1472,8 +1472,8 @@ XPCShellDirProvider::GetFiles(const char* prop, nsISimpleEnumerator** result) { nsCOMPtr appDir; bool exists; if (mAppDir && NS_SUCCEEDED(mAppDir->Clone(getter_AddRefs(appDir))) && - NS_SUCCEEDED(appDir->AppendNative(NS_LITERAL_CSTRING("defaults"))) && - NS_SUCCEEDED(appDir->AppendNative(NS_LITERAL_CSTRING("preferences"))) && + NS_SUCCEEDED(appDir->AppendNative("defaults"_ns)) && + NS_SUCCEEDED(appDir->AppendNative("preferences"_ns)) && NS_SUCCEEDED(appDir->Exists(&exists)) && exists) { dirs.AppendObject(appDir); return NS_NewArrayEnumerator(result, dirs, NS_GET_IID(nsIFile)); @@ -1494,7 +1494,7 @@ XPCShellDirProvider::GetFiles(const char* prop, nsISimpleEnumerator** result) { if (mGREDir) { mGREDir->Clone(getter_AddRefs(file)); if (NS_SUCCEEDED(mGREDir->Clone(getter_AddRefs(file)))) { - file->AppendNative(NS_LITERAL_CSTRING("plugins")); + file->AppendNative("plugins"_ns); if (NS_SUCCEEDED(file->Exists(&exists)) && exists) { dirs.AppendObject(file); } diff --git a/js/xpconnect/src/nsXPConnect.cpp b/js/xpconnect/src/nsXPConnect.cpp index bdcbbda8bf64..496e16aa9645 100644 --- a/js/xpconnect/src/nsXPConnect.cpp +++ b/js/xpconnect/src/nsXPConnect.cpp @@ -191,8 +191,7 @@ void xpc::ErrorNote::Init(JSErrorNotes::Note* aNote) { void xpc::ErrorReport::Init(JSErrorReport* aReport, const char* aToStringResult, bool aIsChrome, uint64_t aWindowID) { xpc::ErrorBase::Init(aReport); - mCategory = aIsChrome ? NS_LITERAL_CSTRING("chrome javascript") - : NS_LITERAL_CSTRING("content javascript"); + mCategory = aIsChrome ? "chrome javascript"_ns : "content javascript"_ns; mWindowID = aWindowID; if (aToStringResult) { @@ -231,8 +230,7 @@ void xpc::ErrorReport::Init(JSErrorReport* aReport, const char* aToStringResult, void xpc::ErrorReport::Init(JSContext* aCx, mozilla::dom::Exception* aException, bool aIsChrome, uint64_t aWindowID) { - mCategory = aIsChrome ? NS_LITERAL_CSTRING("chrome javascript") - : NS_LITERAL_CSTRING("content javascript"); + mCategory = aIsChrome ? "chrome javascript"_ns : "content javascript"_ns; mWindowID = aWindowID; aException->GetErrorMessage(mErrorMsg); @@ -328,7 +326,7 @@ void xpc::ErrorReport::LogToConsoleWithStack( mIsWarning ? nsIScriptError::warningFlag : nsIScriptError::errorFlag; nsresult rv = errorObject->InitWithWindowID( mErrorMsg, mFileName, mSourceLine, mLineNumber, mColumn, flags, mCategory, - mWindowID, mCategory.Equals(NS_LITERAL_CSTRING("chrome javascript"))); + mWindowID, mCategory.Equals("chrome javascript"_ns)); NS_ENSURE_SUCCESS_VOID(rv); rv = errorObject->InitSourceId(mSourceId); @@ -756,7 +754,7 @@ nsXPConnect::EvalInSandboxObject(const nsAString& source, const char* filename, if (filename) { filenameStr.Assign(filename); } else { - filenameStr = NS_LITERAL_CSTRING("x-bogus://XPConnect/Sandbox"); + filenameStr = "x-bogus://XPConnect/Sandbox"_ns; } return EvalInSandbox(cx, sandbox, source, filenameStr, 1, /* enforceFilenameRestrictions */ true, rval); diff --git a/js/xpconnect/src/xpcprivate.h b/js/xpconnect/src/xpcprivate.h index 05787633335c..c8b7b0371a1d 100644 --- a/js/xpconnect/src/xpcprivate.h +++ b/js/xpconnect/src/xpcprivate.h @@ -2735,9 +2735,9 @@ class RealmPrivate { if (jsLocationURI) { // We cannot call into JS-implemented nsIURI objects, because // we are iterating over the JS heap at this point. - location = NS_LITERAL_CSTRING(""); + location = ""_ns; } else if (NS_FAILED(locationURI->GetSpec(location))) { - location = NS_LITERAL_CSTRING(""); + location = ""_ns; } } return location; diff --git a/js/xpconnect/wrappers/AccessCheck.cpp b/js/xpconnect/wrappers/AccessCheck.cpp index 6019b6e7070b..2acfe70d8c87 100644 --- a/js/xpconnect/wrappers/AccessCheck.cpp +++ b/js/xpconnect/wrappers/AccessCheck.cpp @@ -135,7 +135,7 @@ void AccessCheck::reportCrossOriginDenial(JSContext* cx, JS::HandleId id, nsAutoCString message; if (JSID_IS_VOID(id)) { - message = NS_LITERAL_CSTRING("Permission denied to access object"); + message = "Permission denied to access object"_ns; } else { // We want to use JS_ValueToSource here, because that most closely // matches what AutoEnterPolicy::reportErrorIfExceptionIsNotPending @@ -146,10 +146,8 @@ void AccessCheck::reportCrossOriginDenial(JSContext* cx, JS::HandleId id, if (!idStr || !propName.init(cx, idStr)) { return; } - message = NS_LITERAL_CSTRING("Permission denied to ") + accessType + - NS_LITERAL_CSTRING(" property ") + - NS_ConvertUTF16toUTF8(propName) + - NS_LITERAL_CSTRING(" on cross-origin object"); + message = "Permission denied to "_ns + accessType + " property "_ns + + NS_ConvertUTF16toUTF8(propName) + " on cross-origin object"_ns; } ErrorResult rv; rv.ThrowSecurityError(message); diff --git a/layout/base/AccessibleCaret.cpp b/layout/base/AccessibleCaret.cpp index 1bdd6ef63ffc..4a7053a5a88b 100644 --- a/layout/base/AccessibleCaret.cpp +++ b/layout/base/AccessibleCaret.cpp @@ -113,16 +113,16 @@ nsAutoString AccessibleCaret::AppearanceString(Appearance aAppearance) { switch (aAppearance) { case Appearance::None: case Appearance::NormalNotShown: - string = NS_LITERAL_STRING("none"); + string = u"none"_ns; break; case Appearance::Normal: - string = NS_LITERAL_STRING("normal"); + string = u"normal"_ns; break; case Appearance::Right: - string = NS_LITERAL_STRING("right"); + string = u"right"_ns; break; case Appearance::Left: - string = NS_LITERAL_STRING("left"); + string = u"left"_ns; break; } return string; @@ -167,8 +167,8 @@ void AccessibleCaret::EnsureApzAware() { // the element already. if (!CaretElement().IsApzAware()) { // FIXME(emilio): Is this needed anymore? - CaretElement().AddEventListener(NS_LITERAL_STRING("touchstart"), - mDummyTouchListener, false); + CaretElement().AddEventListener(u"touchstart"_ns, mDummyTouchListener, + false); } } @@ -206,8 +206,8 @@ already_AddRefed AccessibleCaret::CreateCaretElement( ErrorResult rv; RefPtr parent = aDocument->CreateHTMLElement(nsGkAtoms::div); - parent->ClassList()->Add(NS_LITERAL_STRING("moz-accessiblecaret"), rv); - parent->ClassList()->Add(NS_LITERAL_STRING("none"), rv); + parent->ClassList()->Add(u"moz-accessiblecaret"_ns, rv); + parent->ClassList()->Add(u"none"_ns, rv); auto CreateAndAppendChildElement = [aDocument, &parent](const nsLiteralString& aElementId) { @@ -223,8 +223,8 @@ already_AddRefed AccessibleCaret::CreateCaretElement( } void AccessibleCaret::RemoveCaretElement(Document* aDocument) { - CaretElement().RemoveEventListener(NS_LITERAL_STRING("touchstart"), - mDummyTouchListener, false); + CaretElement().RemoveEventListener(u"touchstart"_ns, mDummyTouchListener, + false); aDocument->RemoveAnonymousContent(*mCaretElementHolder, IgnoreErrors()); } diff --git a/layout/base/AccessibleCaretManager.cpp b/layout/base/AccessibleCaretManager.cpp index a9946eaeaba4..c5d173bfec1c 100644 --- a/layout/base/AccessibleCaretManager.cpp +++ b/layout/base/AccessibleCaretManager.cpp @@ -926,8 +926,7 @@ void AccessibleCaretManager::SetSelectionDragState(bool aState) const { bool AccessibleCaretManager::IsPhoneNumber(nsAString& aCandidate) const { RefPtr doc = mPresShell->GetDocument(); - nsAutoString phoneNumberRegex( - NS_LITERAL_STRING("(^\\+)?[0-9 ,\\-.()*#pw]{1,30}$")); + nsAutoString phoneNumberRegex(u"(^\\+)?[0-9 ,\\-.()*#pw]{1,30}$"_ns); return nsContentUtils::IsPatternMatching(aCandidate, phoneNumberRegex, doc) .valueOr(false); } @@ -937,10 +936,10 @@ void AccessibleCaretManager::SelectMoreIfPhoneNumber() const { if (IsPhoneNumber(selectedText)) { SetSelectionDirection(eDirNext); - ExtendPhoneNumberSelection(NS_LITERAL_STRING("forward")); + ExtendPhoneNumberSelection(u"forward"_ns); SetSelectionDirection(eDirPrevious); - ExtendPhoneNumberSelection(NS_LITERAL_STRING("backward")); + ExtendPhoneNumberSelection(u"backward"_ns); SetSelectionDirection(eDirNext); } @@ -972,8 +971,8 @@ void AccessibleCaretManager::ExtendPhoneNumberSelection( nsAutoString oldSelectedText = StringifiedSelection(); // Extend the selection by one char. - selection->Modify(NS_LITERAL_STRING("extend"), aDirection, - NS_LITERAL_STRING("character"), IgnoreErrors()); + selection->Modify(u"extend"_ns, aDirection, u"character"_ns, + IgnoreErrors()); if (IsTerminated()) { return; } @@ -1463,7 +1462,7 @@ void AccessibleCaretManager::DispatchCaretStateChangedEvent( init.mSelectedTextContent = StringifiedSelection(); RefPtr event = CaretStateChangedEvent::Constructor( - doc, NS_LITERAL_STRING("mozcaretstatechanged"), init); + doc, u"mozcaretstatechanged"_ns, init); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; diff --git a/layout/base/GeckoMVMContext.cpp b/layout/base/GeckoMVMContext.cpp index 3c2e8ceba698..665d346781d7 100644 --- a/layout/base/GeckoMVMContext.cpp +++ b/layout/base/GeckoMVMContext.cpp @@ -131,7 +131,7 @@ bool GeckoMVMContext::IsInReaderMode() const { if (NS_FAILED(mDocument->GetDocumentURI(uri))) { return false; } - static auto readerModeUriPrefix = NS_LITERAL_STRING("about:reader"); + static auto readerModeUriPrefix = u"about:reader"_ns; return StringBeginsWith(uri, readerModeUriPrefix); } diff --git a/layout/base/LayoutTelemetryTools.cpp b/layout/base/LayoutTelemetryTools.cpp index 90fe2a3200d3..bc219512cd43 100644 --- a/layout/base/LayoutTelemetryTools.cpp +++ b/layout/base/LayoutTelemetryTools.cpp @@ -20,17 +20,17 @@ static nsLiteralCString SubsystemTelemetryKey(LayoutSubsystem aSubsystem) { default: MOZ_CRASH("Unexpected LayoutSubsystem value"); case LayoutSubsystem::Restyle: - return nsLiteralCString("Restyle"); + return "Restyle"_ns; case LayoutSubsystem::Reflow: - return nsLiteralCString("ReflowOther"); + return "ReflowOther"_ns; case LayoutSubsystem::ReflowFlex: - return nsLiteralCString("ReflowFlex"); + return "ReflowFlex"_ns; case LayoutSubsystem::ReflowGrid: - return nsLiteralCString("ReflowGrid"); + return "ReflowGrid"_ns; case LayoutSubsystem::ReflowTable: - return nsLiteralCString("ReflowTable"); + return "ReflowTable"_ns; case LayoutSubsystem::ReflowText: - return nsLiteralCString("ReflowText"); + return "ReflowText"_ns; } } @@ -70,9 +70,9 @@ void Data::PingReqsPerFlushTelemetry(FlushType aFlushType) { auto styleFlushReqs = mReqsPerFlush[FlushKind::Style].value(); auto layoutFlushReqs = mReqsPerFlush[FlushKind::Layout].value(); Telemetry::Accumulate(Telemetry::PRESSHELL_REQS_PER_LAYOUT_FLUSH, - NS_LITERAL_CSTRING("Style"), styleFlushReqs); + "Style"_ns, styleFlushReqs); Telemetry::Accumulate(Telemetry::PRESSHELL_REQS_PER_LAYOUT_FLUSH, - NS_LITERAL_CSTRING("Layout"), layoutFlushReqs); + "Layout"_ns, layoutFlushReqs); mReqsPerFlush[FlushKind::Style] = SaturateUint8(0); mReqsPerFlush[FlushKind::Layout] = SaturateUint8(0); } else { @@ -87,15 +87,15 @@ void Data::PingFlushPerTickTelemetry(FlushType aFlushType) { auto flushKind = ToKind(aFlushType); auto styleFlushes = mFlushesPerTick[FlushKind::Style].value(); if (styleFlushes > 0) { - Telemetry::Accumulate(Telemetry::PRESSHELL_FLUSHES_PER_TICK, - NS_LITERAL_CSTRING("Style"), styleFlushes); + Telemetry::Accumulate(Telemetry::PRESSHELL_FLUSHES_PER_TICK, "Style"_ns, + styleFlushes); mFlushesPerTick[FlushKind::Style] = SaturateUint8(0); } auto layoutFlushes = mFlushesPerTick[FlushKind::Layout].value(); if (flushKind == FlushKind::Layout && layoutFlushes > 0) { - Telemetry::Accumulate(Telemetry::PRESSHELL_FLUSHES_PER_TICK, - NS_LITERAL_CSTRING("Layout"), layoutFlushes); + Telemetry::Accumulate(Telemetry::PRESSHELL_FLUSHES_PER_TICK, "Layout"_ns, + layoutFlushes); mFlushesPerTick[FlushKind::Layout] = SaturateUint8(0); } } diff --git a/layout/base/MobileViewportManager.cpp b/layout/base/MobileViewportManager.cpp index a77825fb9215..10ccb6cd447a 100644 --- a/layout/base/MobileViewportManager.cpp +++ b/layout/base/MobileViewportManager.cpp @@ -22,10 +22,10 @@ static mozilla::LazyLogModule sApzMvmLog("apz.mobileviewport"); NS_IMPL_ISUPPORTS(MobileViewportManager, nsIDOMEventListener, nsIObserver) -#define DOM_META_ADDED NS_LITERAL_STRING("DOMMetaAdded") -#define DOM_META_CHANGED NS_LITERAL_STRING("DOMMetaChanged") -#define LOAD NS_LITERAL_STRING("load") -#define BEFORE_FIRST_PAINT NS_LITERAL_CSTRING("before-first-paint") +#define DOM_META_ADDED u"DOMMetaAdded"_ns +#define DOM_META_CHANGED u"DOMMetaChanged"_ns +#define LOAD u"load"_ns +#define BEFORE_FIRST_PAINT "before-first-paint"_ns using namespace mozilla; using namespace mozilla::dom; diff --git a/layout/base/PresShell.cpp b/layout/base/PresShell.cpp index f27e23155e23..d6ab7963f657 100644 --- a/layout/base/PresShell.cpp +++ b/layout/base/PresShell.cpp @@ -1228,9 +1228,7 @@ void PresShell::Destroy() { !uri->SchemeIs("resource") && !(uri->SchemeIs("moz-extension") && (NS_SUCCEEDED(uri->GetFilePath(path)) && - StringEndsWith( - path, - NS_LITERAL_CSTRING("/_generated_background_page.html"))))) { + StringEndsWith(path, "/_generated_background_page.html"_ns)))) { Telemetry::Accumulate(Telemetry::BASE_FONT_FAMILIES_PER_PAGE, stats->mBaseFonts); Telemetry::Accumulate(Telemetry::LANGPACK_FONT_FAMILIES_PER_PAGE, @@ -3130,7 +3128,7 @@ nsresult PresShell::GoToAnchor(const nsAString& aAnchorName, bool aScroll, NS_NAMED_LITERAL_STRING(nameSpace, "http://www.w3.org/1999/xhtml"); // Get the list of anchor elements nsCOMPtr list = - mDocument->GetElementsByTagNameNS(nameSpace, NS_LITERAL_STRING("a")); + mDocument->GetElementsByTagNameNS(nameSpace, u"a"_ns); // Loop through the anchors looking for the first one with the given name. for (uint32_t i = 0; true; i++) { nsIContent* node = list->Item(i); @@ -6210,7 +6208,7 @@ void PresShell::Paint(nsView* aViewToPaint, const nsRegion& aDirtyRegion, if (contentRoot) { uri = contentRoot->GetDocumentURI(); } - url = uri ? uri->GetSpecOrDefault() : NS_LITERAL_CSTRING("N/A"); + url = uri ? uri->GetSpecOrDefault() : "N/A"_ns; #ifdef MOZ_GECKO_PROFILER AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING("PresShell::Paint", GRAPHICS, url); #endif @@ -9469,8 +9467,7 @@ bool PresShell::DoReflow(nsIFrame* target, bool aInterruptible, #ifdef MOZ_GECKO_PROFILER nsIURI* uri = mDocument->GetDocumentURI(); AUTO_PROFILER_LABEL_DYNAMIC_NSCSTRING( - "Reflow", LAYOUT_Reflow, - uri ? uri->GetSpecOrDefault() : NS_LITERAL_CSTRING("N/A")); + "Reflow", LAYOUT_Reflow, uri ? uri->GetSpecOrDefault() : "N/A"_ns); #endif LAYOUT_TELEMETRY_RECORD_BASE(Reflow); diff --git a/layout/base/ZoomConstraintsClient.cpp b/layout/base/ZoomConstraintsClient.cpp index 699e99692277..d1952a0a87e9 100644 --- a/layout/base/ZoomConstraintsClient.cpp +++ b/layout/base/ZoomConstraintsClient.cpp @@ -29,11 +29,11 @@ static mozilla::LazyLogModule sApzZoomLog("apz.zoom"); NS_IMPL_ISUPPORTS(ZoomConstraintsClient, nsIDOMEventListener, nsIObserver) -#define DOM_META_ADDED NS_LITERAL_STRING("DOMMetaAdded") -#define DOM_META_CHANGED NS_LITERAL_STRING("DOMMetaChanged") -#define FULLSCREEN_CHANGED NS_LITERAL_STRING("fullscreenchange") -#define BEFORE_FIRST_PAINT NS_LITERAL_CSTRING("before-first-paint") -#define NS_PREF_CHANGED NS_LITERAL_CSTRING("nsPref:changed") +#define DOM_META_ADDED u"DOMMetaAdded"_ns +#define DOM_META_CHANGED u"DOMMetaChanged"_ns +#define FULLSCREEN_CHANGED u"fullscreenchange"_ns +#define BEFORE_FIRST_PAINT "before-first-paint"_ns +#define NS_PREF_CHANGED "nsPref:changed"_ns using namespace mozilla; using namespace mozilla::dom; diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp index f9e5162c5685..4fcdc5627b81 100644 --- a/layout/base/nsCSSFrameConstructor.cpp +++ b/layout/base/nsCSSFrameConstructor.cpp @@ -2226,8 +2226,8 @@ nsIFrame* nsCSSFrameConstructor::ConstructDocElementFrame( if (bodyWM != docElementWM) { nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Layout"), - mDocument, nsContentUtils::eLAYOUT_PROPERTIES, + nsIScriptError::warningFlag, "Layout"_ns, mDocument, + nsContentUtils::eLAYOUT_PROPERTIES, "PrincipalWritingModePropagationWarning"); } @@ -4059,7 +4059,7 @@ nsCSSFrameConstructor::FindXULButtonData(const Element& aElement, # ifdef MOZ_THUNDERBIRD if (aElement.AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("menu-button"), eCaseMatters)) { + u"menu-button"_ns, eCaseMatters)) { return &sXULMenuData; } # endif diff --git a/layout/base/nsDocumentViewer.cpp b/layout/base/nsDocumentViewer.cpp index 88c9c95c2b0f..8d45f3da0c41 100644 --- a/layout/base/nsDocumentViewer.cpp +++ b/layout/base/nsDocumentViewer.cpp @@ -494,11 +494,9 @@ namespace mozilla { class AutoPrintEventDispatcher { public: explicit AutoPrintEventDispatcher(Document* aTop) : mTop(aTop) { - DispatchEventToWindowTree(NS_LITERAL_STRING("beforeprint")); - } - ~AutoPrintEventDispatcher() { - DispatchEventToWindowTree(NS_LITERAL_STRING("afterprint")); + DispatchEventToWindowTree(u"beforeprint"_ns); } + ~AutoPrintEventDispatcher() { DispatchEventToWindowTree(u"afterprint"_ns); } private: static CallState CollectDocuments(Document& aDoc, @@ -668,10 +666,8 @@ void nsDocumentViewer::RemoveFocusListener() { std::move(mFocusListener)) { oldListener->Disconnect(); if (mDocument) { - mDocument->RemoveEventListener(NS_LITERAL_STRING("focus"), oldListener, - false); - mDocument->RemoveEventListener(NS_LITERAL_STRING("blur"), oldListener, - false); + mDocument->RemoveEventListener(u"focus"_ns, oldListener, false); + mDocument->RemoveEventListener(u"blur"_ns, oldListener, false); } } } @@ -680,10 +676,8 @@ void nsDocumentViewer::ReinitializeFocusListener() { RemoveFocusListener(); mFocusListener = new nsDocViewerFocusListener(this); if (mDocument) { - mDocument->AddEventListener(NS_LITERAL_STRING("focus"), mFocusListener, - false, false); - mDocument->AddEventListener(NS_LITERAL_STRING("blur"), mFocusListener, - false, false); + mDocument->AddEventListener(u"focus"_ns, mFocusListener, false, false); + mDocument->AddEventListener(u"blur"_ns, mFocusListener, false, false); } } @@ -1282,7 +1276,7 @@ nsresult nsDocumentViewer::PermitUnloadInternal(uint32_t* aPermitUnloadFlags, nsPresContext* presContext = mDocument->GetPresContext(); RefPtr event = new BeforeUnloadEvent(mDocument, presContext, nullptr); - event->InitEvent(NS_LITERAL_STRING("beforeunload"), false, true); + event->InitEvent(u"beforeunload"_ns, false, true); // Dispatching to |window|, but using |document| as the target. event->SetTarget(mDocument); @@ -3154,7 +3148,7 @@ NS_IMETHODIMP nsDocViewerSelectionListener::NotifySelectionChanged( // might need another update string for simple selection changes, but that // would be expenseive. if (mSelectionWasCollapsed != selectionCollapsed) { - domWindow->UpdateCommands(NS_LITERAL_STRING("select"), selection, aReason); + domWindow->UpdateCommands(u"select"_ns, selection, aReason); mSelectionWasCollapsed = selectionCollapsed; } diff --git a/layout/base/nsPresContext.cpp b/layout/base/nsPresContext.cpp index 302f6295327e..5f7f9d3099da 100644 --- a/layout/base/nsPresContext.cpp +++ b/layout/base/nsPresContext.cpp @@ -522,7 +522,7 @@ void nsPresContext::PreferenceChanged(const char* aPrefName) { mMissingFonts = nullptr; } } - if (StringBeginsWith(prefName, NS_LITERAL_CSTRING("font.")) || + if (StringBeginsWith(prefName, "font."_ns) || prefName.EqualsLiteral("intl.accept_languages")) { // Changes to font family preferences don't change anything in the // computed style data, so the style system won't generate a reflow @@ -534,14 +534,14 @@ void nsPresContext::PreferenceChanged(const char* aPrefName) { // bother (yet, anyway). mPrefChangePendingNeedsReflow = true; } - if (StringBeginsWith(prefName, NS_LITERAL_CSTRING("bidi."))) { + if (StringBeginsWith(prefName, "bidi."_ns)) { // Changes to bidi prefs need to trigger a reflow (see bug 443629) mPrefChangePendingNeedsReflow = true; // Changes to bidi.numeral also needs to empty the text run cache. // This is handled in gfxTextRunWordCache.cpp. } - if (StringBeginsWith(prefName, NS_LITERAL_CSTRING("gfx.font_rendering."))) { + if (StringBeginsWith(prefName, "gfx.font_rendering."_ns)) { // Changes to font_rendering prefs need to trigger a reflow mPrefChangePendingNeedsReflow = true; } @@ -2352,8 +2352,7 @@ void nsPresContext::NotifyNonBlankPaint() { void nsPresContext::NotifyContentfulPaint() { if (!mHadContentfulPaint) { #if defined(MOZ_WIDGET_ANDROID) - (new AsyncEventDispatcher(mDocument, - NS_LITERAL_STRING("MozFirstContentfulPaint"), + (new AsyncEventDispatcher(mDocument, u"MozFirstContentfulPaint"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes)) ->PostDOMEvent(); #endif diff --git a/layout/base/nsRefreshDriver.cpp b/layout/base/nsRefreshDriver.cpp index 51c19a8dae33..172473618943 100644 --- a/layout/base/nsRefreshDriver.cpp +++ b/layout/base/nsRefreshDriver.cpp @@ -2226,17 +2226,17 @@ void nsRefreshDriver::Tick(VsyncId aId, TimeStamp aNowTime) { phasePercent); }; - record(NS_LITERAL_CSTRING("Event"), phaseMetrics[0]); - record(NS_LITERAL_CSTRING("Style"), phaseMetrics[1]); - record(NS_LITERAL_CSTRING("Reflow"), phaseMetrics[2]); - record(NS_LITERAL_CSTRING("Display"), phaseMetrics[3]); - record(NS_LITERAL_CSTRING("Paint"), phasePaint); + record("Event"_ns, phaseMetrics[0]); + record("Style"_ns, phaseMetrics[1]); + record("Reflow"_ns, phaseMetrics[2]); + record("Display"_ns, phaseMetrics[3]); + record("Paint"_ns, phasePaint); // Explicitly record the time unaccounted for. double other = totalMs - std::accumulate(phaseMetrics, ArrayEnd(phaseMetrics), 0.0) - phasePaint; - record(NS_LITERAL_CSTRING("Other"), other); + record("Other"_ns, other); } if (mNotifyDOMContentFlushed) { diff --git a/layout/build/nsContentDLF.cpp b/layout/build/nsContentDLF.cpp index c83f878c207c..a3e22f12739d 100644 --- a/layout/build/nsContentDLF.cpp +++ b/layout/build/nsContentDLF.cpp @@ -114,10 +114,10 @@ nsContentDLF::CreateInstance(const char* aCommand, nsIChannel* aChannel, // Also note the lifetime of "type" allows us to safely use "get()" here. contentType = type; } else { - viewSourceChannel->SetContentType(NS_LITERAL_CSTRING(TEXT_PLAIN)); + viewSourceChannel->SetContentType(nsLiteralCString(TEXT_PLAIN)); } } else if (aContentType.EqualsLiteral(VIEWSOURCE_CONTENT_TYPE)) { - aChannel->SetContentType(NS_LITERAL_CSTRING(TEXT_PLAIN)); + aChannel->SetContentType(nsLiteralCString(TEXT_PLAIN)); contentType = TEXT_PLAIN; } @@ -237,7 +237,7 @@ already_AddRefed nsContentDLF::CreateBlankDocument( // initialize nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("about:blank")); + NS_NewURI(getter_AddRefs(uri), "about:blank"_ns); if (!uri) { return nullptr; } diff --git a/layout/forms/nsColorControlFrame.cpp b/layout/forms/nsColorControlFrame.cpp index b51e79c39817..d279d178a8cf 100644 --- a/layout/forms/nsColorControlFrame.cpp +++ b/layout/forms/nsColorControlFrame.cpp @@ -48,7 +48,7 @@ void nsColorControlFrame::DestroyFrom(nsIFrame* aDestructRoot, #ifdef DEBUG_FRAME_DUMP nsresult nsColorControlFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ColorControl"), aResult); + return MakeFrameName(u"ColorControl"_ns, aResult); } #endif @@ -105,7 +105,7 @@ nsresult nsColorControlFrame::UpdateColor() { // Set the background-color CSS property of the swatch element to this color. return mColorContent->SetAttr(kNameSpaceID_None, nsGkAtoms::style, - NS_LITERAL_STRING("background-color:") + color, + u"background-color:"_ns + color, /* aNotify */ true); } diff --git a/layout/forms/nsComboboxControlFrame.cpp b/layout/forms/nsComboboxControlFrame.cpp index 839018809aa8..1db74daef707 100644 --- a/layout/forms/nsComboboxControlFrame.cpp +++ b/layout/forms/nsComboboxControlFrame.cpp @@ -869,7 +869,7 @@ void nsComboboxControlFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsComboboxControlFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ComboboxControl"), aResult); + return MakeFrameName(u"ComboboxControl"_ns, aResult); } #endif @@ -1174,20 +1174,18 @@ nsresult nsComboboxControlFrame::CreateAnonymousContent( // make someone to listen to the button. If its pressed by someone like // Accessibility then open or close the combo box. mButtonListener = new nsComboButtonListener(this); - mButtonContent->AddEventListener(NS_LITERAL_STRING("click"), mButtonListener, - false, false); + mButtonContent->AddEventListener(u"click"_ns, mButtonListener, false, false); - mButtonContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("button"), false); + mButtonContent->SetAttr(kNameSpaceID_None, nsGkAtoms::type, u"button"_ns, + false); // Set tabindex="-1" so that the button is not tabbable - mButtonContent->SetAttr(kNameSpaceID_None, nsGkAtoms::tabindex, - NS_LITERAL_STRING("-1"), false); + mButtonContent->SetAttr(kNameSpaceID_None, nsGkAtoms::tabindex, u"-1"_ns, + false); WritingMode wm = GetWritingMode(); if (wm.IsVertical()) { mButtonContent->SetAttr(kNameSpaceID_None, nsGkAtoms::orientation, - wm.IsVerticalRL() ? NS_LITERAL_STRING("left") - : NS_LITERAL_STRING("right"), + wm.IsVerticalRL() ? u"left"_ns : u"right"_ns, false); } @@ -1226,7 +1224,7 @@ class nsComboboxDisplayFrame final : public nsBlockFrame { #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("ComboboxDisplay"), aResult); + return MakeFrameName(u"ComboboxDisplay"_ns, aResult); } #endif @@ -1572,9 +1570,8 @@ nsComboboxControlFrame::OnOptionSelected(int32_t aIndex, bool aSelected) { void nsComboboxControlFrame::FireValueChangeEvent() { // Fire ValueChange event to indicate data value of combo box has changed - nsContentUtils::AddScriptRunner( - new AsyncEventDispatcher(mContent, NS_LITERAL_STRING("ValueChange"), - CanBubble::eYes, ChromeOnlyDispatch::eNo)); + nsContentUtils::AddScriptRunner(new AsyncEventDispatcher( + mContent, u"ValueChange"_ns, CanBubble::eYes, ChromeOnlyDispatch::eNo)); } void nsComboboxControlFrame::OnContentReset() { diff --git a/layout/forms/nsDateTimeControlFrame.h b/layout/forms/nsDateTimeControlFrame.h index 27d56e23121c..45f457781447 100644 --- a/layout/forms/nsDateTimeControlFrame.h +++ b/layout/forms/nsDateTimeControlFrame.h @@ -43,7 +43,7 @@ class nsDateTimeControlFrame final : public nsContainerFrame { #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("DateTimeControl"), aResult); + return MakeFrameName(u"DateTimeControl"_ns, aResult); } #endif diff --git a/layout/forms/nsFieldSetFrame.h b/layout/forms/nsFieldSetFrame.h index 2336e843ad42..b664097729e8 100644 --- a/layout/forms/nsFieldSetFrame.h +++ b/layout/forms/nsFieldSetFrame.h @@ -77,7 +77,7 @@ class nsFieldSetFrame final : public nsContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("FieldSet"), aResult); + return MakeFrameName(u"FieldSet"_ns, aResult); } #endif diff --git a/layout/forms/nsFileControlFrame.cpp b/layout/forms/nsFileControlFrame.cpp index e251ed03ad88..89e9958a3b6e 100644 --- a/layout/forms/nsFileControlFrame.cpp +++ b/layout/forms/nsFileControlFrame.cpp @@ -191,10 +191,8 @@ void nsFileControlFrame::DestroyFrom(nsIFrame* aDestructRoot, // Remove the events. if (mContent) { - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("drop"), - mMouseListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("dragover"), - mMouseListener, false); + mContent->RemoveSystemEventListener(u"drop"_ns, mMouseListener, false); + mContent->RemoveSystemEventListener(u"dragover"_ns, mMouseListener, false); } aPostDestroyData.AddAnonymousContent(mTextContent.forget()); @@ -281,10 +279,8 @@ nsresult nsFileControlFrame::CreateAnonymousContent( aElements.AppendElement(mTextContent); // We should be able to interact with the element by doing drag and drop. - mContent->AddSystemEventListener(NS_LITERAL_STRING("drop"), mMouseListener, - false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("dragover"), - mMouseListener, false); + mContent->AddSystemEventListener(u"drop"_ns, mMouseListener, false); + mContent->AddSystemEventListener(u"dragover"_ns, mMouseListener, false); SyncDisabledState(); @@ -367,7 +363,7 @@ nsFileControlFrame::DnDListener::HandleEvent(Event* aEvent) { bool supportsMultiple = inputElement->HasAttr(kNameSpaceID_None, nsGkAtoms::multiple); if (!CanDropTheseFiles(dataTransfer, supportsMultiple)) { - dataTransfer->SetDropEffect(NS_LITERAL_STRING("none")); + dataTransfer->SetDropEffect(u"none"_ns); aEvent->StopPropagation(); return NS_OK; } @@ -441,7 +437,7 @@ nsFileControlFrame::DnDListener::HandleEvent(Event* aEvent) { "Failed to dispatch input event"); nsContentUtils::DispatchTrustedEvent( inputElement->OwnerDoc(), static_cast(inputElement), - NS_LITERAL_STRING("change"), CanBubble::eYes, Cancelable::eNo); + u"change"_ns, CanBubble::eYes, Cancelable::eNo); } } @@ -555,7 +551,7 @@ void nsFileControlFrame::ContentStatesChanged(EventStates aStates) { #ifdef DEBUG_FRAME_DUMP nsresult nsFileControlFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("FileControl"), aResult); + return MakeFrameName(u"FileControl"_ns, aResult); } #endif diff --git a/layout/forms/nsGfxButtonControlFrame.cpp b/layout/forms/nsGfxButtonControlFrame.cpp index 9414c045ca61..a27b20f6317c 100644 --- a/layout/forms/nsGfxButtonControlFrame.cpp +++ b/layout/forms/nsGfxButtonControlFrame.cpp @@ -34,7 +34,7 @@ void nsGfxButtonControlFrame::DestroyFrom(nsIFrame* aDestructRoot, #ifdef DEBUG_FRAME_DUMP nsresult nsGfxButtonControlFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ButtonControl"), aResult); + return MakeFrameName(u"ButtonControl"_ns, aResult); } #endif diff --git a/layout/forms/nsHTMLButtonControlFrame.h b/layout/forms/nsHTMLButtonControlFrame.h index b8ce1d9081a4..58cdf0090a2f 100644 --- a/layout/forms/nsHTMLButtonControlFrame.h +++ b/layout/forms/nsHTMLButtonControlFrame.h @@ -74,7 +74,7 @@ class nsHTMLButtonControlFrame : public nsContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("HTMLButtonControl"), aResult); + return MakeFrameName(u"HTMLButtonControl"_ns, aResult); } #endif diff --git a/layout/forms/nsImageControlFrame.cpp b/layout/forms/nsImageControlFrame.cpp index a72988134e97..15bbe40911aa 100644 --- a/layout/forms/nsImageControlFrame.cpp +++ b/layout/forms/nsImageControlFrame.cpp @@ -43,7 +43,7 @@ class nsImageControlFrame final : public nsImageFrame, #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const final { - return MakeFrameName(NS_LITERAL_STRING("ImageControl"), aResult); + return MakeFrameName(u"ImageControl"_ns, aResult); } #endif diff --git a/layout/forms/nsLegendFrame.cpp b/layout/forms/nsLegendFrame.cpp index 6b11cb590531..e42ed047382d 100644 --- a/layout/forms/nsLegendFrame.cpp +++ b/layout/forms/nsLegendFrame.cpp @@ -88,6 +88,6 @@ dom::HTMLLegendElement::LegendAlignValue nsLegendFrame::GetLogicalAlign( #ifdef DEBUG_FRAME_DUMP nsresult nsLegendFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Legend"), aResult); + return MakeFrameName(u"Legend"_ns, aResult); } #endif diff --git a/layout/forms/nsListControlFrame.cpp b/layout/forms/nsListControlFrame.cpp index cf2e75646a41..c9d8407347fe 100644 --- a/layout/forms/nsListControlFrame.cpp +++ b/layout/forms/nsListControlFrame.cpp @@ -129,20 +129,15 @@ void nsListControlFrame::DestroyFrom(nsIFrame* aDestructRoot, mEventListener->SetFrame(nullptr); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), - mEventListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("keypress"), - mEventListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"), - mEventListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mouseup"), - mEventListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mousemove"), - mEventListener, false); + mContent->RemoveSystemEventListener(u"keydown"_ns, mEventListener, false); + mContent->RemoveSystemEventListener(u"keypress"_ns, mEventListener, false); + mContent->RemoveSystemEventListener(u"mousedown"_ns, mEventListener, false); + mContent->RemoveSystemEventListener(u"mouseup"_ns, mEventListener, false); + mContent->RemoveSystemEventListener(u"mousemove"_ns, mEventListener, false); if (ShouldFireDropDownEvent()) { nsContentUtils::AddScriptRunner( - new AsyncEventDispatcher(mContent, NS_LITERAL_STRING("mozhidedropdown"), + new AsyncEventDispatcher(mContent, u"mozhidedropdown"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes)); } @@ -928,16 +923,14 @@ void nsListControlFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, // we need to hook up our listeners before the editor is initialized mEventListener = new nsListEventListener(this); - mContent->AddSystemEventListener(NS_LITERAL_STRING("keydown"), mEventListener, - false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("keypress"), - mEventListener, false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("mousedown"), - mEventListener, false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("mouseup"), mEventListener, - false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("mousemove"), - mEventListener, false, false); + mContent->AddSystemEventListener(u"keydown"_ns, mEventListener, false, false); + mContent->AddSystemEventListener(u"keypress"_ns, mEventListener, false, + false); + mContent->AddSystemEventListener(u"mousedown"_ns, mEventListener, false, + false); + mContent->AddSystemEventListener(u"mouseup"_ns, mEventListener, false, false); + mContent->AddSystemEventListener(u"mousemove"_ns, mEventListener, false, + false); mStartSelectionIndex = kNothingSelected; mEndSelectionIndex = kNothingSelected; @@ -1290,8 +1283,8 @@ void nsListControlFrame::FireOnInputAndOnChange() { // Dispatch the change event. nsContentUtils::DispatchTrustedEvent(element->OwnerDoc(), element, - NS_LITERAL_STRING("change"), - CanBubble::eYes, Cancelable::eNo); + u"change"_ns, CanBubble::eYes, + Cancelable::eNo); } NS_IMETHODIMP_(void) @@ -1418,7 +1411,7 @@ void nsListControlFrame::DidReflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsListControlFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ListControl"), aResult); + return MakeFrameName(u"ListControl"_ns, aResult); } #endif @@ -1602,7 +1595,7 @@ void nsListControlFrame::FireMenuItemActiveEvent() { return; } - FireDOMEvent(NS_LITERAL_STRING("DOMMenuItemActive"), optionContent); + FireDOMEvent(u"DOMMenuItemActive"_ns, optionContent); } #endif @@ -1641,11 +1634,10 @@ static bool FireShowDropDownEvent(nsIContent* aContent, bool aShow, if (ShouldFireDropDownEvent()) { nsString eventName; if (aShow) { - eventName = aIsSourceTouchEvent - ? NS_LITERAL_STRING("mozshowdropdown-sourcetouch") - : NS_LITERAL_STRING("mozshowdropdown"); + eventName = aIsSourceTouchEvent ? u"mozshowdropdown-sourcetouch"_ns + : u"mozshowdropdown"_ns; } else { - eventName = NS_LITERAL_STRING("mozhidedropdown"); + eventName = u"mozhidedropdown"_ns; } nsContentUtils::DispatchChromeEvent(aContent->OwnerDoc(), aContent, eventName, CanBubble::eYes, diff --git a/layout/forms/nsMeterFrame.h b/layout/forms/nsMeterFrame.h index 2311929d79c7..de222a8e7088 100644 --- a/layout/forms/nsMeterFrame.h +++ b/layout/forms/nsMeterFrame.h @@ -35,7 +35,7 @@ class nsMeterFrame final : public nsContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Meter"), aResult); + return MakeFrameName(u"Meter"_ns, aResult); } #endif diff --git a/layout/forms/nsNumberControlFrame.cpp b/layout/forms/nsNumberControlFrame.cpp index 919f94e2986f..1141f52534f4 100644 --- a/layout/forms/nsNumberControlFrame.cpp +++ b/layout/forms/nsNumberControlFrame.cpp @@ -57,7 +57,7 @@ already_AddRefed nsNumberControlFrame::MakeAnonymousElement( if (aPseudoType == PseudoStyleType::mozNumberSpinDown || aPseudoType == PseudoStyleType::mozNumberSpinUp) { resultElement->SetAttr(kNameSpaceID_None, nsGkAtoms::aria_hidden, - NS_LITERAL_STRING("true"), false); + u"true"_ns, false); } if (aParent) { diff --git a/layout/forms/nsNumberControlFrame.h b/layout/forms/nsNumberControlFrame.h index 51af66d5614c..fe80b6c235fa 100644 --- a/layout/forms/nsNumberControlFrame.h +++ b/layout/forms/nsNumberControlFrame.h @@ -62,7 +62,7 @@ class nsNumberControlFrame final : public nsTextControlFrame { #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("NumberControl"), aResult); + return MakeFrameName(u"NumberControl"_ns, aResult); } #endif diff --git a/layout/forms/nsProgressFrame.h b/layout/forms/nsProgressFrame.h index 9388677646dd..77ae3341d7d9 100644 --- a/layout/forms/nsProgressFrame.h +++ b/layout/forms/nsProgressFrame.h @@ -40,7 +40,7 @@ class nsProgressFrame final : public nsContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Progress"), aResult); + return MakeFrameName(u"Progress"_ns, aResult); } #endif diff --git a/layout/forms/nsRangeFrame.cpp b/layout/forms/nsRangeFrame.cpp index 579338789e53..1e747590f276 100644 --- a/layout/forms/nsRangeFrame.cpp +++ b/layout/forms/nsRangeFrame.cpp @@ -69,8 +69,7 @@ void nsRangeFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, if (!mDummyTouchListener) { mDummyTouchListener = new DummyTouchListener(); } - aContent->AddEventListener(NS_LITERAL_STRING("touchstart"), - mDummyTouchListener, false); + aContent->AddEventListener(u"touchstart"_ns, mDummyTouchListener, false); return nsContainerFrame::Init(aContent, aParent, aPrevInFlow); } @@ -81,8 +80,7 @@ void nsRangeFrame::DestroyFrom(nsIFrame* aDestructRoot, "nsRangeFrame should not have continuations; if it does we " "need to call RegUnregAccessKey only for the first."); - mContent->RemoveEventListener(NS_LITERAL_STRING("touchstart"), - mDummyTouchListener, false); + mContent->RemoveEventListener(u"touchstart"_ns, mDummyTouchListener, false); nsCheckboxRadioFrame::RegUnRegAccessKey(static_cast(this), false); aPostDestroyData.AddAnonymousContent(mTrackDiv.forget()); diff --git a/layout/forms/nsRangeFrame.h b/layout/forms/nsRangeFrame.h index 2a837e473b29..5498b90c9a50 100644 --- a/layout/forms/nsRangeFrame.h +++ b/layout/forms/nsRangeFrame.h @@ -57,7 +57,7 @@ class nsRangeFrame final : public nsContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Range"), aResult); + return MakeFrameName(u"Range"_ns, aResult); } #endif diff --git a/layout/generic/BlockReflowInput.cpp b/layout/generic/BlockReflowInput.cpp index 9f8968197f6f..eccef4a85cee 100644 --- a/layout/generic/BlockReflowInput.cpp +++ b/layout/generic/BlockReflowInput.cpp @@ -817,9 +817,9 @@ bool BlockReflowInput::FlowAndPlaceFloat(nsIFrame* aFloat) { // FIXME(emilio, bug 1426747): This looks fishy. nsIContent* content = prevFrame->GetContent(); if (content && content->IsElement() && - content->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::align, - NS_LITERAL_STRING("left"), eIgnoreCase)) { + content->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::align, u"left"_ns, + eIgnoreCase)) { keepFloatOnSameLine = true; // don't advance to next line (IE quirkie behaviour) // it breaks rule CSS2/9.5.1/1, but what the hell diff --git a/layout/generic/ColumnSetWrapperFrame.cpp b/layout/generic/ColumnSetWrapperFrame.cpp index 9a7735f74b71..8e0664d49a90 100644 --- a/layout/generic/ColumnSetWrapperFrame.cpp +++ b/layout/generic/ColumnSetWrapperFrame.cpp @@ -97,7 +97,7 @@ void ColumnSetWrapperFrame::AppendDirectlyOwnedAnonBoxes( #ifdef DEBUG_FRAME_DUMP nsresult ColumnSetWrapperFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ColumnSetWrapper"), aResult); + return MakeFrameName(u"ColumnSetWrapper"_ns, aResult); } #endif diff --git a/layout/generic/DetailsFrame.h b/layout/generic/DetailsFrame.h index 90735ca5ad82..f2b8e1be5147 100644 --- a/layout/generic/DetailsFrame.h +++ b/layout/generic/DetailsFrame.h @@ -30,7 +30,7 @@ class DetailsFrame final : public nsBlockFrame, #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Details"), aResult); + return MakeFrameName(u"Details"_ns, aResult); } #endif diff --git a/layout/generic/ScrollAnchorContainer.cpp b/layout/generic/ScrollAnchorContainer.cpp index ad408287a29f..499199adf2d6 100644 --- a/layout/generic/ScrollAnchorContainer.cpp +++ b/layout/generic/ScrollAnchorContainer.cpp @@ -361,7 +361,7 @@ void ScrollAnchorContainer::AdjustmentMade(nscoord aAdjustment) { arguments.AppendElement()->AppendFloat(cssPixels); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Layout"), + nsIScriptError::warningFlag, "Layout"_ns, Frame()->PresContext()->Document(), nsContentUtils::eLAYOUT_PROPERTIES, "ScrollAnchoringDisabledInContainer", arguments); } diff --git a/layout/generic/ScrollbarActivity.cpp b/layout/generic/ScrollbarActivity.cpp index b8a996bc5308..5a8c9a2693bc 100644 --- a/layout/generic/ScrollbarActivity.cpp +++ b/layout/generic/ScrollbarActivity.cpp @@ -183,8 +183,7 @@ void ScrollbarActivity::StartListeningForScrollAreaEvents() { if (mListeningForScrollAreaEvents) return; nsIFrame* scrollArea = do_QueryFrame(mScrollableFrame); - scrollArea->GetContent()->AddEventListener(NS_LITERAL_STRING("mousemove"), - this, true); + scrollArea->GetContent()->AddEventListener(u"mousemove"_ns, this, true); mListeningForScrollAreaEvents = true; } @@ -192,28 +191,27 @@ void ScrollbarActivity::StopListeningForScrollAreaEvents() { if (!mListeningForScrollAreaEvents) return; nsIFrame* scrollArea = do_QueryFrame(mScrollableFrame); - scrollArea->GetContent()->RemoveEventListener(NS_LITERAL_STRING("mousemove"), - this, true); + scrollArea->GetContent()->RemoveEventListener(u"mousemove"_ns, this, true); mListeningForScrollAreaEvents = false; } void ScrollbarActivity::AddScrollbarEventListeners( dom::EventTarget* aScrollbar) { if (aScrollbar) { - aScrollbar->AddEventListener(NS_LITERAL_STRING("mousedown"), this, true); - aScrollbar->AddEventListener(NS_LITERAL_STRING("mouseup"), this, true); - aScrollbar->AddEventListener(NS_LITERAL_STRING("mouseover"), this, true); - aScrollbar->AddEventListener(NS_LITERAL_STRING("mouseout"), this, true); + aScrollbar->AddEventListener(u"mousedown"_ns, this, true); + aScrollbar->AddEventListener(u"mouseup"_ns, this, true); + aScrollbar->AddEventListener(u"mouseover"_ns, this, true); + aScrollbar->AddEventListener(u"mouseout"_ns, this, true); } } void ScrollbarActivity::RemoveScrollbarEventListeners( dom::EventTarget* aScrollbar) { if (aScrollbar) { - aScrollbar->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, true); - aScrollbar->RemoveEventListener(NS_LITERAL_STRING("mouseup"), this, true); - aScrollbar->RemoveEventListener(NS_LITERAL_STRING("mouseover"), this, true); - aScrollbar->RemoveEventListener(NS_LITERAL_STRING("mouseout"), this, true); + aScrollbar->RemoveEventListener(u"mousedown"_ns, this, true); + aScrollbar->RemoveEventListener(u"mouseup"_ns, this, true); + aScrollbar->RemoveEventListener(u"mouseover"_ns, this, true); + aScrollbar->RemoveEventListener(u"mouseout"_ns, this, true); } } @@ -273,8 +271,7 @@ static void SetBooleanAttribute(Element* aElement, nsAtom* aAttribute, bool aValue) { if (aElement) { if (aValue) { - aElement->SetAttr(kNameSpaceID_None, aAttribute, - NS_LITERAL_STRING("true"), true); + aElement->SetAttr(kNameSpaceID_None, aAttribute, u"true"_ns, true); } else { aElement->UnsetAttr(kNameSpaceID_None, aAttribute, true); } @@ -300,8 +297,7 @@ static void SetOpacityOnElement(nsIContent* aContent, double aOpacity) { nsICSSDeclaration* decl = inlineStyleContent->Style(); nsAutoCString str; str.AppendFloat(aOpacity); - decl->SetProperty(NS_LITERAL_CSTRING("opacity"), str, EmptyString(), - IgnoreErrors()); + decl->SetProperty("opacity"_ns, str, EmptyString(), IgnoreErrors()); } } @@ -331,7 +327,7 @@ static void UnsetOpacityOnElement(nsIContent* aContent) { if (inlineStyleContent) { nsICSSDeclaration* decl = inlineStyleContent->Style(); nsAutoString dummy; - decl->RemoveProperty(NS_LITERAL_CSTRING("opacity"), dummy, IgnoreErrors()); + decl->RemoveProperty("opacity"_ns, dummy, IgnoreErrors()); } } diff --git a/layout/generic/ViewportFrame.cpp b/layout/generic/ViewportFrame.cpp index f9999a551585..3d333e68c1d6 100644 --- a/layout/generic/ViewportFrame.cpp +++ b/layout/generic/ViewportFrame.cpp @@ -406,6 +406,6 @@ nsSize ViewportFrame::AdjustViewportSizeForFixedPosition( #ifdef DEBUG_FRAME_DUMP nsresult ViewportFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Viewport"), aResult); + return MakeFrameName(u"Viewport"_ns, aResult); } #endif diff --git a/layout/generic/nsBackdropFrame.cpp b/layout/generic/nsBackdropFrame.cpp index 487f53fef47e..986ade50250b 100644 --- a/layout/generic/nsBackdropFrame.cpp +++ b/layout/generic/nsBackdropFrame.cpp @@ -16,7 +16,7 @@ NS_IMPL_FRAMEARENA_HELPERS(nsBackdropFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsBackdropFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Backdrop"), aResult); + return MakeFrameName(u"Backdrop"_ns, aResult); } #endif diff --git a/layout/generic/nsBlockFrame.cpp b/layout/generic/nsBlockFrame.cpp index 414ba47d2dbb..7199a5d7177c 100644 --- a/layout/generic/nsBlockFrame.cpp +++ b/layout/generic/nsBlockFrame.cpp @@ -540,7 +540,7 @@ void nsBlockFrame::List(FILE* out, const char* aPrefix, } nsresult nsBlockFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Block"), aResult); + return MakeFrameName(u"Block"_ns, aResult); } #endif diff --git a/layout/generic/nsBulletFrame.cpp b/layout/generic/nsBulletFrame.cpp index c58ee41cebed..72c60bccb54d 100644 --- a/layout/generic/nsBulletFrame.cpp +++ b/layout/generic/nsBulletFrame.cpp @@ -89,7 +89,7 @@ void nsBulletFrame::DestroyFrom(nsIFrame* aDestructRoot, #ifdef DEBUG_FRAME_DUMP nsresult nsBulletFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Bullet"), aResult); + return MakeFrameName(u"Bullet"_ns, aResult); } #endif diff --git a/layout/generic/nsCanvasFrame.cpp b/layout/generic/nsCanvasFrame.cpp index 598f1d56e705..066509b813d4 100644 --- a/layout/generic/nsCanvasFrame.cpp +++ b/layout/generic/nsCanvasFrame.cpp @@ -65,7 +65,7 @@ void nsCanvasFrame::ShowCustomContentContainer() { void nsCanvasFrame::HideCustomContentContainer() { if (mCustomContentContainer) { mCustomContentContainer->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, - NS_LITERAL_STRING("true"), true); + u"true"_ns, true); } } @@ -116,11 +116,10 @@ nsresult nsCanvasFrame::CreateAnonymousContent( // Do not create an accessible object for the container. mCustomContentContainer->SetAttr(kNameSpaceID_None, nsGkAtoms::role, - NS_LITERAL_STRING("presentation"), false); + u"presentation"_ns, false); - mCustomContentContainer->SetAttr( - kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("moz-custom-content-container"), false); + mCustomContentContainer->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, + u"moz-custom-content-container"_ns, false); // Only create a frame for mCustomContentContainer if it has some children. if (doc->GetAnonymousContents().IsEmpty()) { @@ -171,12 +170,12 @@ nsresult nsCanvasFrame::CreateAnonymousContent( dom::NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); - mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::_default, - NS_LITERAL_STRING("true"), false); + mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::_default, u"true"_ns, + false); // Set the page attribute so XULTooltipElement::PostHandleEvent will find // the text for the tooltip from the currently hovered element. - mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::page, - NS_LITERAL_STRING("true"), false); + mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::page, u"true"_ns, + false); mTooltipContent->SetProperty(nsGkAtoms::docLevelNativeAnonymousContent, reinterpret_cast(true)); @@ -855,6 +854,6 @@ nsresult nsCanvasFrame::GetContentForEvent(WidgetEvent* aEvent, #ifdef DEBUG_FRAME_DUMP nsresult nsCanvasFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Canvas"), aResult); + return MakeFrameName(u"Canvas"_ns, aResult); } #endif diff --git a/layout/generic/nsColumnSetFrame.h b/layout/generic/nsColumnSetFrame.h index 4703ce1ca8e2..abd18bef2051 100644 --- a/layout/generic/nsColumnSetFrame.h +++ b/layout/generic/nsColumnSetFrame.h @@ -70,7 +70,7 @@ class nsColumnSetFrame final : public nsContainerFrame { #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("ColumnSet"), aResult); + return MakeFrameName(u"ColumnSet"_ns, aResult); } #endif diff --git a/layout/generic/nsFirstLetterFrame.cpp b/layout/generic/nsFirstLetterFrame.cpp index db5dab792b8d..0b845cbbeaa8 100644 --- a/layout/generic/nsFirstLetterFrame.cpp +++ b/layout/generic/nsFirstLetterFrame.cpp @@ -38,7 +38,7 @@ NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsFirstLetterFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Letter"), aResult); + return MakeFrameName(u"Letter"_ns, aResult); } #endif diff --git a/layout/generic/nsFlexContainerFrame.cpp b/layout/generic/nsFlexContainerFrame.cpp index 07d0b3d59750..c2f16ec736e4 100644 --- a/layout/generic/nsFlexContainerFrame.cpp +++ b/layout/generic/nsFlexContainerFrame.cpp @@ -2566,7 +2566,7 @@ void nsFlexContainerFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, #ifdef DEBUG_FRAME_DUMP nsresult nsFlexContainerFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("FlexContainer"), aResult); + return MakeFrameName(u"FlexContainer"_ns, aResult); } #endif diff --git a/layout/generic/nsFrame.cpp b/layout/generic/nsFrame.cpp index 205f49576185..e0f2fdfec6d5 100644 --- a/layout/generic/nsFrame.cpp +++ b/layout/generic/nsFrame.cpp @@ -7751,7 +7751,7 @@ void nsIFrame::ListWithMatchedRules(FILE* out, const char* aPrefix) const { } nsresult nsIFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Frame"), aResult); + return MakeFrameName(u"Frame"_ns, aResult); } nsresult nsIFrame::MakeFrameName(const nsAString& aType, diff --git a/layout/generic/nsFrameSetFrame.cpp b/layout/generic/nsFrameSetFrame.cpp index 0b0c91319521..8eb7885adcd7 100644 --- a/layout/generic/nsFrameSetFrame.cpp +++ b/layout/generic/nsFrameSetFrame.cpp @@ -133,7 +133,7 @@ class nsHTMLFramesetBlankFrame final : public nsLeafFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("FramesetBlank"), aResult); + return MakeFrameName(u"FramesetBlank"_ns, aResult); } #endif @@ -1057,7 +1057,7 @@ void nsHTMLFramesetFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsHTMLFramesetFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Frameset"), aResult); + return MakeFrameName(u"Frameset"_ns, aResult); } #endif @@ -1468,7 +1468,7 @@ Maybe nsHTMLFramesetBorderFrame::GetCursor(const nsPoint&) { #ifdef DEBUG_FRAME_DUMP nsresult nsHTMLFramesetBorderFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("FramesetBorder"), aResult); + return MakeFrameName(u"FramesetBorder"_ns, aResult); } #endif diff --git a/layout/generic/nsGfxScrollFrame.cpp b/layout/generic/nsGfxScrollFrame.cpp index 5f21e6c1c714..57d1718d5ee0 100644 --- a/layout/generic/nsGfxScrollFrame.cpp +++ b/layout/generic/nsGfxScrollFrame.cpp @@ -1295,7 +1295,7 @@ void nsHTMLScrollFrame::DidReflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsHTMLScrollFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("HTMLScroll"), aResult); + return MakeFrameName(u"HTMLScroll"_ns, aResult); } #endif @@ -1735,7 +1735,7 @@ nsSize nsXULScrollFrame::GetXULMaxSize(nsBoxLayoutState& aState) { #ifdef DEBUG_FRAME_DUMP nsresult nsXULScrollFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("XULScroll"), aResult); + return MakeFrameName(u"XULScroll"_ns, aResult); } #endif @@ -2008,30 +2008,30 @@ ComputeBezierAnimationSettingsForOrigin(ScrollOrigin aOrigin) { nsAutoCString prefBase; switch (aOrigin) { case ScrollOrigin::Pixels: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.pixels"); + prefBase = "general.smoothScroll.pixels"_ns; break; case ScrollOrigin::Lines: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.lines"); + prefBase = "general.smoothScroll.lines"_ns; break; case ScrollOrigin::Pages: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.pages"); + prefBase = "general.smoothScroll.pages"_ns; break; case ScrollOrigin::MouseWheel: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.mouseWheel"); + prefBase = "general.smoothScroll.mouseWheel"_ns; break; case ScrollOrigin::Scrollbars: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.scrollbars"); + prefBase = "general.smoothScroll.scrollbars"_ns; break; default: - prefBase = NS_LITERAL_CSTRING("general.smoothScroll.other"); + prefBase = "general.smoothScroll.other"_ns; break; } isOriginSmoothnessEnabled = Preferences::GetBool(prefBase.get(), kDefaultIsSmoothEnabled); if (isOriginSmoothnessEnabled) { - nsAutoCString prefMin = prefBase + NS_LITERAL_CSTRING(".durationMinMS"); - nsAutoCString prefMax = prefBase + NS_LITERAL_CSTRING(".durationMaxMS"); + nsAutoCString prefMin = prefBase + ".durationMinMS"_ns; + nsAutoCString prefMax = prefBase + ".durationMaxMS"_ns; minMS = Preferences::GetInt(prefMin.get(), kDefaultMinMS); maxMS = Preferences::GetInt(prefMax.get(), kDefaultMaxMS); @@ -4880,8 +4880,8 @@ void ScrollFrameHelper::FireScrollEndEvent() { mScrollEndEvent = nullptr; nsContentUtils::DispatchEventOnlyToChrome( - mOuter->GetContent()->OwnerDoc(), mOuter->GetContent(), - NS_LITERAL_STRING("scrollend"), CanBubble::eYes, Cancelable::eNo); + mOuter->GetContent()->OwnerDoc(), mOuter->GetContent(), u"scrollend"_ns, + CanBubble::eYes, Cancelable::eNo); } void ScrollFrameHelper::ReloadChildFrames() { @@ -4931,8 +4931,8 @@ already_AddRefed ScrollFrameHelper::MakeScrollbar( aNodeInfo->Equals(nsGkAtoms::scrollbar, nullptr, kNameSpaceID_XUL)); static constexpr nsLiteralString kOrientValues[2] = { - NS_LITERAL_STRING("horizontal"), - NS_LITERAL_STRING("vertical"), + u"horizontal"_ns, + u"vertical"_ns, }; aKey = AnonymousContentKey::Type_Scrollbar; @@ -4953,14 +4953,12 @@ already_AddRefed ScrollFrameHelper::MakeScrollbar( e->SetAttr(kNameSpaceID_None, nsGkAtoms::orient, kOrientValues[aVertical], false); - e->SetAttr(kNameSpaceID_None, nsGkAtoms::clickthrough, - NS_LITERAL_STRING("always"), false); + e->SetAttr(kNameSpaceID_None, nsGkAtoms::clickthrough, u"always"_ns, false); if (mIsRoot) { e->SetProperty(nsGkAtoms::docLevelNativeAnonymousContent, reinterpret_cast(true)); - e->SetAttr(kNameSpaceID_None, nsGkAtoms::root_, NS_LITERAL_STRING("true"), - false); + e->SetAttr(kNameSpaceID_None, nsGkAtoms::root_, u"true"_ns, false); // Don't bother making style caching take [root="true"] styles into account. aKey = AnonymousContentKey::None; @@ -5116,11 +5114,11 @@ nsresult ScrollFrameHelper::CreateAnonymousContent( mCollapsedResizer = true; } else { mResizerContent->SetAttr(kNameSpaceID_None, nsGkAtoms::element, - NS_LITERAL_STRING("_parent"), false); + u"_parent"_ns, false); } mResizerContent->SetAttr(kNameSpaceID_None, nsGkAtoms::clickthrough, - NS_LITERAL_STRING("always"), false); + u"always"_ns, false); aElements.AppendElement(ContentInfo(mResizerContent, key)); } @@ -6450,8 +6448,7 @@ void ScrollFrameHelper::SetScrollbarEnabled(Element* aElement, if (aMaxPos) { aElement->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled, true); } else { - aElement->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, - NS_LITERAL_STRING("true"), true); + aElement->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, u"true"_ns, true); } MOZ_ASSERT(ShellIsAlive(weakShell), "pres shell was destroyed by scrolling"); } diff --git a/layout/generic/nsGridContainerFrame.cpp b/layout/generic/nsGridContainerFrame.cpp index 81d9a25aa4f2..2b4a38ac5ed5 100644 --- a/layout/generic/nsGridContainerFrame.cpp +++ b/layout/generic/nsGridContainerFrame.cpp @@ -3269,11 +3269,11 @@ struct MOZ_STACK_CLASS nsGridContainerFrame::Grid { } static bool IsNameWithEndSuffix(nsAtom* aString, uint32_t* aIndex) { - return IsNameWithSuffix(aString, NS_LITERAL_STRING("-end"), aIndex); + return IsNameWithSuffix(aString, u"-end"_ns, aIndex); } static bool IsNameWithStartSuffix(nsAtom* aString, uint32_t* aIndex) { - return IsNameWithSuffix(aString, NS_LITERAL_STRING("-start"), aIndex); + return IsNameWithSuffix(aString, u"-start"_ns, aIndex); } // Return the relevant parent LineNameMap for the given subgrid axis aAxis. @@ -9467,7 +9467,7 @@ void nsGridContainerFrame::CalculateBaselines( #ifdef DEBUG_FRAME_DUMP nsresult nsGridContainerFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("GridContainer"), aResult); + return MakeFrameName(u"GridContainer"_ns, aResult); } void nsGridContainerFrame::ExtraContainerFrameInfo(nsACString& aTo) const { diff --git a/layout/generic/nsHTMLCanvasFrame.cpp b/layout/generic/nsHTMLCanvasFrame.cpp index cff0a619f4e3..aa8bb0db0254 100644 --- a/layout/generic/nsHTMLCanvasFrame.cpp +++ b/layout/generic/nsHTMLCanvasFrame.cpp @@ -601,6 +601,6 @@ a11y::AccType nsHTMLCanvasFrame::AccessibleType() { #ifdef DEBUG_FRAME_DUMP nsresult nsHTMLCanvasFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("HTMLCanvas"), aResult); + return MakeFrameName(u"HTMLCanvas"_ns, aResult); } #endif diff --git a/layout/generic/nsImageFrame.cpp b/layout/generic/nsImageFrame.cpp index 084414ab585c..c2af757395a5 100644 --- a/layout/generic/nsImageFrame.cpp +++ b/layout/generic/nsImageFrame.cpp @@ -2417,7 +2417,7 @@ void nsImageFrame::OnVisibilityChange( #ifdef DEBUG_FRAME_DUMP nsresult nsImageFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ImageFrame"), aResult); + return MakeFrameName(u"ImageFrame"_ns, aResult); } void nsImageFrame::List(FILE* out, const char* aPrefix, diff --git a/layout/generic/nsImageMap.cpp b/layout/generic/nsImageMap.cpp index e1032a274da2..0dddeb1e5de8 100644 --- a/layout/generic/nsImageMap.cpp +++ b/layout/generic/nsImageMap.cpp @@ -73,12 +73,12 @@ inline bool is_space(char c) { static void logMessage(nsIContent* aContent, const nsAString& aCoordsSpec, int32_t aFlags, const char* aMessageName) { nsContentUtils::ReportToConsole( - aFlags, NS_LITERAL_CSTRING("Layout: ImageMap"), aContent->OwnerDoc(), + aFlags, "Layout: ImageMap"_ns, aContent->OwnerDoc(), nsContentUtils::eLAYOUT_PROPERTIES, aMessageName, nsTArray(), /* params */ nullptr, - PromiseFlatString(NS_LITERAL_STRING("coords=\"") + aCoordsSpec + - NS_LITERAL_STRING("\""))); /* source line */ + PromiseFlatString(u"coords=\""_ns + aCoordsSpec + + u"\""_ns)); /* source line */ } void Area::ParseCoords(const nsAString& aSpec) { @@ -628,8 +628,8 @@ void nsImageMap::AreaRemoved(HTMLAreaElement* aArea) { aArea->SetPrimaryFrame(nullptr); } - aArea->RemoveSystemEventListener(NS_LITERAL_STRING("focus"), this, false); - aArea->RemoveSystemEventListener(NS_LITERAL_STRING("blur"), this, false); + aArea->RemoveSystemEventListener(u"focus"_ns, this, false); + aArea->RemoveSystemEventListener(u"blur"_ns, this, false); } void nsImageMap::FreeAreas() { @@ -721,8 +721,8 @@ void nsImageMap::AddArea(HTMLAreaElement* aArea) { } // Add focus listener to track area focus changes - aArea->AddSystemEventListener(NS_LITERAL_STRING("focus"), this, false, false); - aArea->AddSystemEventListener(NS_LITERAL_STRING("blur"), this, false, false); + aArea->AddSystemEventListener(u"focus"_ns, this, false, false); + aArea->AddSystemEventListener(u"blur"_ns, this, false, false); // This is a nasty hack. It needs to go away: see bug 135040. Once this is // removed, the code added to RestyleManager::RestyleElement, diff --git a/layout/generic/nsInlineFrame.cpp b/layout/generic/nsInlineFrame.cpp index a56aad766f59..dfb312846a00 100644 --- a/layout/generic/nsInlineFrame.cpp +++ b/layout/generic/nsInlineFrame.cpp @@ -48,7 +48,7 @@ NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsInlineFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Inline"), aResult); + return MakeFrameName(u"Inline"_ns, aResult); } #endif @@ -969,7 +969,7 @@ void nsFirstLineFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, #ifdef DEBUG_FRAME_DUMP nsresult nsFirstLineFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Line"), aResult); + return MakeFrameName(u"Line"_ns, aResult); } #endif diff --git a/layout/generic/nsPageContentFrame.cpp b/layout/generic/nsPageContentFrame.cpp index 81df5e77d374..1b7683fc8af1 100644 --- a/layout/generic/nsPageContentFrame.cpp +++ b/layout/generic/nsPageContentFrame.cpp @@ -123,6 +123,6 @@ void nsPageContentFrame::AppendDirectlyOwnedAnonBoxes( #ifdef DEBUG_FRAME_DUMP nsresult nsPageContentFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("PageContent"), aResult); + return MakeFrameName(u"PageContent"_ns, aResult); } #endif diff --git a/layout/generic/nsPageFrame.cpp b/layout/generic/nsPageFrame.cpp index e9fb910dae97..1184d503eb7f 100644 --- a/layout/generic/nsPageFrame.cpp +++ b/layout/generic/nsPageFrame.cpp @@ -167,7 +167,7 @@ void nsPageFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsPageFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Page"), aResult); + return MakeFrameName(u"Page"_ns, aResult); } #endif @@ -713,6 +713,6 @@ void nsPageBreakFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsPageBreakFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("PageBreak"), aResult); + return MakeFrameName(u"PageBreak"_ns, aResult); } #endif diff --git a/layout/generic/nsPageSequenceFrame.cpp b/layout/generic/nsPageSequenceFrame.cpp index f077548eec05..a665c863bcbf 100644 --- a/layout/generic/nsPageSequenceFrame.cpp +++ b/layout/generic/nsPageSequenceFrame.cpp @@ -329,7 +329,7 @@ void nsPageSequenceFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsPageSequenceFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("PageSequence"), aResult); + return MakeFrameName(u"PageSequence"_ns, aResult); } #endif diff --git a/layout/generic/nsPlaceholderFrame.cpp b/layout/generic/nsPlaceholderFrame.cpp index ab47165f83d0..d27e461e7df8 100644 --- a/layout/generic/nsPlaceholderFrame.cpp +++ b/layout/generic/nsPlaceholderFrame.cpp @@ -261,7 +261,7 @@ void nsPlaceholderFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder, #ifdef DEBUG_FRAME_DUMP nsresult nsPlaceholderFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Placeholder"), aResult); + return MakeFrameName(u"Placeholder"_ns, aResult); } void nsPlaceholderFrame::List(FILE* out, const char* aPrefix, diff --git a/layout/generic/nsPluginFrame.cpp b/layout/generic/nsPluginFrame.cpp index 230e3284d4d8..c26295950e45 100644 --- a/layout/generic/nsPluginFrame.cpp +++ b/layout/generic/nsPluginFrame.cpp @@ -217,7 +217,7 @@ void nsPluginFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) { #ifdef DEBUG_FRAME_DUMP nsresult nsPluginFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("PluginFrame"), aResult); + return MakeFrameName(u"PluginFrame"_ns, aResult); } #endif @@ -991,8 +991,7 @@ nsresult nsPluginFrame::PluginEventNotifier::Run() { } void nsPluginFrame::NotifyPluginReflowObservers() { - nsContentUtils::AddScriptRunner( - new PluginEventNotifier(NS_LITERAL_STRING("reflow"))); + nsContentUtils::AddScriptRunner(new PluginEventNotifier(u"reflow"_ns)); } void nsPluginFrame::DidSetWidgetGeometry() { diff --git a/layout/generic/nsRubyBaseContainerFrame.cpp b/layout/generic/nsRubyBaseContainerFrame.cpp index af06af5f4315..9ca87b9dff45 100644 --- a/layout/generic/nsRubyBaseContainerFrame.cpp +++ b/layout/generic/nsRubyBaseContainerFrame.cpp @@ -49,7 +49,7 @@ nsContainerFrame* NS_NewRubyBaseContainerFrame(PresShell* aPresShell, #ifdef DEBUG_FRAME_DUMP nsresult nsRubyBaseContainerFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("RubyBaseContainer"), aResult); + return MakeFrameName(u"RubyBaseContainer"_ns, aResult); } #endif diff --git a/layout/generic/nsRubyBaseFrame.cpp b/layout/generic/nsRubyBaseFrame.cpp index c93fb4029785..4350a43a282a 100644 --- a/layout/generic/nsRubyBaseFrame.cpp +++ b/layout/generic/nsRubyBaseFrame.cpp @@ -39,6 +39,6 @@ nsContainerFrame* NS_NewRubyBaseFrame(mozilla::PresShell* aPresShell, #ifdef DEBUG_FRAME_DUMP nsresult nsRubyBaseFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("RubyBase"), aResult); + return MakeFrameName(u"RubyBase"_ns, aResult); } #endif diff --git a/layout/generic/nsRubyFrame.cpp b/layout/generic/nsRubyFrame.cpp index 96a09f581f9a..42ba1ba68d68 100644 --- a/layout/generic/nsRubyFrame.cpp +++ b/layout/generic/nsRubyFrame.cpp @@ -52,7 +52,7 @@ bool nsRubyFrame::IsFrameOfType(uint32_t aFlags) const { #ifdef DEBUG_FRAME_DUMP nsresult nsRubyFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Ruby"), aResult); + return MakeFrameName(u"Ruby"_ns, aResult); } #endif diff --git a/layout/generic/nsRubyTextContainerFrame.cpp b/layout/generic/nsRubyTextContainerFrame.cpp index ac81134459dc..96200b863079 100644 --- a/layout/generic/nsRubyTextContainerFrame.cpp +++ b/layout/generic/nsRubyTextContainerFrame.cpp @@ -41,7 +41,7 @@ nsContainerFrame* NS_NewRubyTextContainerFrame(PresShell* aPresShell, #ifdef DEBUG_FRAME_DUMP nsresult nsRubyTextContainerFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("RubyTextContainer"), aResult); + return MakeFrameName(u"RubyTextContainer"_ns, aResult); } #endif diff --git a/layout/generic/nsRubyTextFrame.cpp b/layout/generic/nsRubyTextFrame.cpp index e1d848a6d84b..afa94853da32 100644 --- a/layout/generic/nsRubyTextFrame.cpp +++ b/layout/generic/nsRubyTextFrame.cpp @@ -42,7 +42,7 @@ bool nsRubyTextFrame::CanContinueTextRun() const { return false; } #ifdef DEBUG_FRAME_DUMP nsresult nsRubyTextFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("RubyText"), aResult); + return MakeFrameName(u"RubyText"_ns, aResult); } #endif diff --git a/layout/generic/nsSubDocumentFrame.cpp b/layout/generic/nsSubDocumentFrame.cpp index 0940f744ce39..ab372a52701b 100644 --- a/layout/generic/nsSubDocumentFrame.cpp +++ b/layout/generic/nsSubDocumentFrame.cpp @@ -618,7 +618,7 @@ void nsSubDocumentFrame::List(FILE* out, const char* aPrefix, } nsresult nsSubDocumentFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("FrameOuter"), aResult); + return MakeFrameName(u"FrameOuter"_ns, aResult); } #endif diff --git a/layout/generic/nsTextFrame.cpp b/layout/generic/nsTextFrame.cpp index 1cebaa4e99f7..64a0b62dca2e 100644 --- a/layout/generic/nsTextFrame.cpp +++ b/layout/generic/nsTextFrame.cpp @@ -2236,14 +2236,14 @@ already_AddRefed BuildTextRunsScanner::BuildTextRunForFrames( if (parent) { nsIContent* content = parent->GetContent(); if (content && content->IsElement()) { - if (content->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::fontstyle_, - NS_LITERAL_STRING("normal"), eCaseMatters)) { + if (content->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::fontstyle_, + u"normal"_ns, eCaseMatters)) { mathFlags |= MathMLTextRunFactory::MATH_FONT_STYLING_NORMAL; } - if (content->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::fontweight_, - NS_LITERAL_STRING("bold"), eCaseMatters)) { + if (content->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::fontweight_, + u"bold"_ns, eCaseMatters)) { mathFlags |= MathMLTextRunFactory::MATH_FONT_WEIGHT_BOLD; } } @@ -4959,8 +4959,8 @@ static bool IsUnderlineRight(const ComputedStyle& aStyle) { return false; } nsDependentAtomString langStr(langAtom); - return (StringBeginsWith(langStr, NS_LITERAL_STRING("ja")) || - StringBeginsWith(langStr, NS_LITERAL_STRING("ko"))) && + return (StringBeginsWith(langStr, u"ja"_ns) || + StringBeginsWith(langStr, u"ko"_ns)) && (langStr.Length() == 2 || langStr[2] == '-'); } @@ -10001,13 +10001,12 @@ void nsTextFrame::ToCString(nsCString& aBuf, } nsresult nsTextFrame::GetFrameName(nsAString& aResult) const { - MakeFrameName(NS_LITERAL_STRING("Text"), aResult); + MakeFrameName(u"Text"_ns, aResult); int32_t totalContentLength; nsAutoCString tmp; ToCString(tmp, &totalContentLength); tmp.SetLength(std::min(tmp.Length(), 50u)); - aResult += NS_LITERAL_STRING("\"") + NS_ConvertASCIItoUTF16(tmp) + - NS_LITERAL_STRING("\""); + aResult += u"\""_ns + NS_ConvertASCIItoUTF16(tmp) + u"\""_ns; return NS_OK; } diff --git a/layout/generic/nsVideoFrame.cpp b/layout/generic/nsVideoFrame.cpp index 6e0c6d11834f..eedb3071813f 100644 --- a/layout/generic/nsVideoFrame.cpp +++ b/layout/generic/nsVideoFrame.cpp @@ -125,7 +125,7 @@ nsresult nsVideoFrame::CreateAnonymousContent( NS_ENSURE_TRUE(mCaptionDiv, NS_ERROR_OUT_OF_MEMORY); nsGenericHTMLElement* div = static_cast(mCaptionDiv.get()); - div->SetClassName(NS_LITERAL_STRING("caption-box")); + div->SetClassName(u"caption-box"_ns); // XXX(Bug 1631371) Check if this should use a fallible operation as it // pretended earlier. @@ -364,8 +364,8 @@ void nsVideoFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aMetrics, if (child->GetSize() != oldChildSize) { const nsString name = child->GetContent() == videoControlsDiv - ? NS_LITERAL_STRING("resizevideocontrols") - : NS_LITERAL_STRING("resizecaption"); + ? u"resizevideocontrols"_ns + : u"resizecaption"_ns; RefPtr event = new DispatchResizeEvent(child->GetContent(), name); nsContentUtils::AddScriptRunner(event); @@ -571,7 +571,7 @@ a11y::AccType nsVideoFrame::AccessibleType() { return a11y::eHTMLMediaType; } #ifdef DEBUG_FRAME_DUMP nsresult nsVideoFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("HTMLVideo"), aResult); + return MakeFrameName(u"HTMLVideo"_ns, aResult); } #endif diff --git a/layout/mathml/nsMathMLChar.cpp b/layout/mathml/nsMathMLChar.cpp index b413af7acc4f..502e233b0cc7 100644 --- a/layout/mathml/nsMathMLChar.cpp +++ b/layout/mathml/nsMathMLChar.cpp @@ -549,7 +549,7 @@ class nsGlyphTableList final : public nsIObserver { nsPropertiesTable mUnicodeTable; - nsGlyphTableList() : mUnicodeTable(NS_LITERAL_CSTRING("Unicode")) {} + nsGlyphTableList() : mUnicodeTable("Unicode"_ns) {} nsresult Initialize(); nsresult Finalize(); @@ -660,7 +660,7 @@ static nsresult InitCharGlobals() { // observer and will be deleted at shutdown. We now add some private // per font-family tables for stretchy operators, in order of preference. // Do not include the Unicode table in this list. - if (!glyphTableList->AddGlyphTable(NS_LITERAL_CSTRING("STIXGeneral"))) { + if (!glyphTableList->AddGlyphTable("STIXGeneral"_ns)) { rv = NS_ERROR_OUT_OF_MEMORY; } @@ -1530,10 +1530,10 @@ nsresult nsMathMLChar::StretchInternal( font.fontlist.GetFontlist()->mNames; for (const FontFamilyName& name : fontlist) { if (StretchEnumContext::EnumCallback(name, name.IsGeneric(), &enumData)) { - if (name.IsNamedFamily(NS_LITERAL_STRING("STIXGeneral"))) { + if (name.IsNamedFamily(u"STIXGeneral"_ns)) { AutoTArray params{ - NS_LITERAL_STRING("https://developer.mozilla.org/docs/Mozilla/" - "MathML_Project/Fonts")}; + u"https://developer.mozilla.org/docs/Mozilla/" + "MathML_Project/Fonts"_ns}; aForFrame->PresContext()->Document()->WarnOnceAbout( dom::Document::eMathML_DeprecatedStixgeneralOperatorStretching, false, params); diff --git a/layout/mathml/nsMathMLContainerFrame.cpp b/layout/mathml/nsMathMLContainerFrame.cpp index c22036f5b0dc..a55c64849806 100644 --- a/layout/mathml/nsMathMLContainerFrame.cpp +++ b/layout/mathml/nsMathMLContainerFrame.cpp @@ -1432,9 +1432,8 @@ void nsMathMLContainerFrame::PropagateFrameFlagFor(nsIFrame* aFrame, nsresult nsMathMLContainerFrame::ReportErrorToConsole( const char* errorMsgId, const nsTArray& aParams) { return nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Layout: MathML"), - mContent->OwnerDoc(), nsContentUtils::eMATHML_PROPERTIES, errorMsgId, - aParams); + nsIScriptError::errorFlag, "Layout: MathML"_ns, mContent->OwnerDoc(), + nsContentUtils::eMATHML_PROPERTIES, errorMsgId, aParams); } nsresult nsMathMLContainerFrame::ReportParseError(const char16_t* aAttribute, diff --git a/layout/mathml/nsMathMLOperators.cpp b/layout/mathml/nsMathMLOperators.cpp index 864323340830..fbfe686e32c8 100644 --- a/layout/mathml/nsMathMLOperators.cpp +++ b/layout/mathml/nsMathMLOperators.cpp @@ -207,7 +207,7 @@ static nsresult InitOperators(void) { nsCOMPtr mathfontProp; rv = NS_LoadPersistentPropertiesFromURISpec( getter_AddRefs(mathfontProp), - NS_LITERAL_CSTRING("resource://gre/res/fonts/mathfont.properties")); + "resource://gre/res/fonts/mathfont.properties"_ns); if (NS_FAILED(rv)) return rv; diff --git a/layout/mathml/nsMathMLmactionFrame.cpp b/layout/mathml/nsMathMLmactionFrame.cpp index 2197667f780d..e5eec1feb9c7 100644 --- a/layout/mathml/nsMathMLmactionFrame.cpp +++ b/layout/mathml/nsMathMLmactionFrame.cpp @@ -75,12 +75,9 @@ nsMathMLmactionFrame::~nsMathMLmactionFrame() { // unregister us as a mouse event listener ... // printf("maction:%p unregistering as mouse event listener ...\n", this); if (mListener) { - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("click"), mListener, - false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mouseover"), - mListener, false); - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mouseout"), - mListener, false); + mContent->RemoveSystemEventListener(u"click"_ns, mListener, false); + mContent->RemoveSystemEventListener(u"mouseover"_ns, mListener, false); + mContent->RemoveSystemEventListener(u"mouseout"_ns, mListener, false); } } @@ -175,12 +172,9 @@ void nsMathMLmactionFrame::SetInitialChildList(ChildListID aListID, // create mouse event listener and register it mListener = new nsMathMLmactionFrame::MouseListener(this); // printf("maction:%p registering as mouse event listener ...\n", this); - mContent->AddSystemEventListener(NS_LITERAL_STRING("click"), mListener, - false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("mouseover"), mListener, - false, false); - mContent->AddSystemEventListener(NS_LITERAL_STRING("mouseout"), mListener, - false, false); + mContent->AddSystemEventListener(u"click"_ns, mListener, false, false); + mContent->AddSystemEventListener(u"mouseover"_ns, mListener, false, false); + mContent->AddSystemEventListener(u"mouseout"_ns, mListener, false, false); } } diff --git a/layout/mathml/nsMathMLmtableFrame.cpp b/layout/mathml/nsMathMLmtableFrame.cpp index 3470fed1c5ec..cb70ec279f33 100644 --- a/layout/mathml/nsMathMLmtableFrame.cpp +++ b/layout/mathml/nsMathMLmtableFrame.cpp @@ -127,9 +127,8 @@ static nsresult ReportParseError(nsIFrame* aFrame, const char16_t* aAttribute, params.AppendElement(nsDependentAtomString(content->NodeInfo()->NameAtom())); return nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("Layout: MathML"), - content->OwnerDoc(), nsContentUtils::eMATHML_PROPERTIES, - "AttributeParsingError", params); + nsIScriptError::errorFlag, "Layout: MathML"_ns, content->OwnerDoc(), + nsContentUtils::eMATHML_PROPERTIES, "AttributeParsingError", params); } // Each rowalign='top bottom' or columnalign='left right center' (from diff --git a/layout/painting/nsCSSRenderingBorders.cpp b/layout/painting/nsCSSRenderingBorders.cpp index b7ec7d42bd57..6f93adc70d1e 100644 --- a/layout/painting/nsCSSRenderingBorders.cpp +++ b/layout/painting/nsCSSRenderingBorders.cpp @@ -2537,7 +2537,7 @@ void nsCSSBorderRenderer::DrawFallbackSolidCorner(mozilla::Side aSide, if (!mPresContext->HasWarnedAboutTooLargeDashedOrDottedRadius()) { mPresContext->SetHasWarnedAboutTooLargeDashedOrDottedRadius(); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("CSS"), mDocument, + nsIScriptError::warningFlag, "CSS"_ns, mDocument, nsContentUtils::eCSS_PROPERTIES, mBorderStyles[aSide] == StyleBorderStyle::Dashed ? "TooLargeDashedRadius" diff --git a/layout/painting/nsDisplayList.cpp b/layout/painting/nsDisplayList.cpp index 8445273dc5a3..03cb633aed50 100644 --- a/layout/painting/nsDisplayList.cpp +++ b/layout/painting/nsDisplayList.cpp @@ -1223,7 +1223,7 @@ void nsDisplayListBuilder::MarkFramesForDisplayList( if (content && content->IsInNativeAnonymousSubtree() && content->IsElement()) { auto classList = content->AsElement()->ClassList(); - if (classList->Contains(NS_LITERAL_STRING("moz-accessiblecaret"))) { + if (classList->Contains(u"moz-accessiblecaret"_ns)) { continue; } } @@ -10007,15 +10007,15 @@ PaintTelemetry::AutoRecordPaint::~AutoRecordPaint() { // If the total time was >= 16ms, then it's likely we missed a frame due to // painting. We bucket these metrics separately. if (totalMs >= 16.0) { - recordLarge(NS_LITERAL_CSTRING("dl"), dlMs); - recordLarge(NS_LITERAL_CSTRING("flb"), flbMs); - recordLarge(NS_LITERAL_CSTRING("fr"), frMs); - recordLarge(NS_LITERAL_CSTRING("r"), rMs); + recordLarge("dl"_ns, dlMs); + recordLarge("flb"_ns, flbMs); + recordLarge("fr"_ns, frMs); + recordLarge("r"_ns, rMs); } else { - recordSmall(NS_LITERAL_CSTRING("dl"), dlMs); - recordSmall(NS_LITERAL_CSTRING("flb"), flbMs); - recordSmall(NS_LITERAL_CSTRING("fr"), frMs); - recordSmall(NS_LITERAL_CSTRING("r"), rMs); + recordSmall("dl"_ns, dlMs); + recordSmall("flb"_ns, flbMs); + recordSmall("fr"_ns, frMs); + recordSmall("r"_ns, rMs); } Telemetry::Accumulate(Telemetry::PAINT_BUILD_LAYERS_TIME, flbMs); diff --git a/layout/printing/PrintPreviewUserEventSuppressor.cpp b/layout/printing/PrintPreviewUserEventSuppressor.cpp index c1f4703c641b..93e3b02f3c6b 100644 --- a/layout/printing/PrintPreviewUserEventSuppressor.cpp +++ b/layout/printing/PrintPreviewUserEventSuppressor.cpp @@ -29,44 +29,35 @@ NS_IMPL_ISUPPORTS(PrintPreviewUserEventSuppressor, nsIDOMEventListener) void PrintPreviewUserEventSuppressor::AddListeners() { if (mEventTarget) { - mEventTarget->AddEventListener(NS_LITERAL_STRING("click"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("contextmenu"), this, - true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("keydown"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("keypress"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("keyup"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mousedown"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mousemove"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mouseout"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mouseover"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mouseup"), this, true); - - mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("keydown"), this, - true); + mEventTarget->AddEventListener(u"click"_ns, this, true); + mEventTarget->AddEventListener(u"contextmenu"_ns, this, true); + mEventTarget->AddEventListener(u"keydown"_ns, this, true); + mEventTarget->AddEventListener(u"keypress"_ns, this, true); + mEventTarget->AddEventListener(u"keyup"_ns, this, true); + mEventTarget->AddEventListener(u"mousedown"_ns, this, true); + mEventTarget->AddEventListener(u"mousemove"_ns, this, true); + mEventTarget->AddEventListener(u"mouseout"_ns, this, true); + mEventTarget->AddEventListener(u"mouseover"_ns, this, true); + mEventTarget->AddEventListener(u"mouseup"_ns, this, true); + + mEventTarget->AddSystemEventListener(u"keydown"_ns, this, true); } } void PrintPreviewUserEventSuppressor::RemoveListeners() { if (mEventTarget) { - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("click"), this, true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("contextmenu"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mousemove"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mouseout"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mouseover"), this, - true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mouseup"), this, true); - - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), this, - true); + mEventTarget->RemoveEventListener(u"click"_ns, this, true); + mEventTarget->RemoveEventListener(u"contextmenu"_ns, this, true); + mEventTarget->RemoveEventListener(u"keydown"_ns, this, true); + mEventTarget->RemoveEventListener(u"keypress"_ns, this, true); + mEventTarget->RemoveEventListener(u"keyup"_ns, this, true); + mEventTarget->RemoveEventListener(u"mousedown"_ns, this, true); + mEventTarget->RemoveEventListener(u"mousemove"_ns, this, true); + mEventTarget->RemoveEventListener(u"mouseout"_ns, this, true); + mEventTarget->RemoveEventListener(u"mouseover"_ns, this, true); + mEventTarget->RemoveEventListener(u"mouseup"_ns, this, true); + + mEventTarget->RemoveSystemEventListener(u"keydown"_ns, this, true); } } diff --git a/layout/printing/nsPrintJob.cpp b/layout/printing/nsPrintJob.cpp index 356b74035140..46fbd7ca445f 100644 --- a/layout/printing/nsPrintJob.cpp +++ b/layout/printing/nsPrintJob.cpp @@ -389,7 +389,7 @@ static bool DocHasPrintCallbackCanvas(Document& aDoc) { // FIXME(emilio): This doesn't account for shadow dom and it's unnecessarily // inefficient. Though I guess it doesn't really matter. RefPtr canvases = - NS_GetContentList(root, kNameSpaceID_XHTML, NS_LITERAL_STRING("canvas")); + NS_GetContentList(root, kNameSpaceID_XHTML, u"canvas"_ns); uint32_t canvasCount = canvases->Length(true); for (uint32_t i = 0; i < canvasCount; ++i) { auto* canvas = HTMLCanvasElement::FromNodeOrNull(canvases->Item(i, false)); @@ -1273,8 +1273,7 @@ void nsPrintJob::FirePrintingErrorEvent(nsresult aPrintError) { JS::Rooted detail( cx, JS::NumberValue(static_cast(aPrintError))); - event->InitCustomEvent(cx, NS_LITERAL_STRING("PrintingError"), false, false, - detail); + event->InitCustomEvent(cx, u"PrintingError"_ns, false, false, detail); event->SetTrusted(true); RefPtr asyncDispatcher = @@ -1629,8 +1628,7 @@ void nsPrintJob::FirePrintPreviewUpdateEvent() { // listener bound to this event and therefore no need to dispatch it. if (mIsDoingPrintPreview && !mIsDoingPrinting) { nsCOMPtr cv = do_QueryInterface(mDocViewerPrint); - (new AsyncEventDispatcher(cv->GetDocument(), - NS_LITERAL_STRING("printPreviewUpdate"), + (new AsyncEventDispatcher(cv->GetDocument(), u"printPreviewUpdate"_ns, CanBubble::eYes, ChromeOnlyDispatch::eYes)) ->RunDOMEventWhenSafe(); } @@ -1812,7 +1810,7 @@ nsresult nsPrintJob::UpdateSelectionAndShrinkPrintObject( nsAutoString contentType; aPO->mPresShell->GetDocument()->GetContentType(contentType); if (contentType.EqualsLiteral("application/xhtml+xml") || - StringBeginsWith(contentType, NS_LITERAL_STRING("text/"))) { + StringBeginsWith(contentType, u"text/"_ns)) { int32_t limitPercent = Preferences::GetInt("print.shrink-to-fit.scale-limit-percent", 20); limitPercent = std::max(0, limitPercent); diff --git a/layout/style/FontFaceSet.cpp b/layout/style/FontFaceSet.cpp index 1a8ca6fd2cb7..44fe0aefae1d 100644 --- a/layout/style/FontFaceSet.cpp +++ b/layout/style/FontFaceSet.cpp @@ -148,8 +148,8 @@ FontFaceSet::FontFaceSet(nsPIDOMWindowInner* aWindow, dom::Document* aDocument) } if (!mDocument->DidFireDOMContentLoaded()) { - mDocument->AddSystemEventListener(NS_LITERAL_STRING("DOMContentLoaded"), - this, false, false); + mDocument->AddSystemEventListener(u"DOMContentLoaded"_ns, this, false, + false); } else { // In some cases we can't rely on CheckLoadingFinished being called from // the refresh driver. For example, documents in display:none iframes. @@ -195,8 +195,7 @@ void FontFaceSet::Disconnect() { void FontFaceSet::RemoveDOMContentLoadedListener() { if (mDocument) { - mDocument->RemoveSystemEventListener(NS_LITERAL_STRING("DOMContentLoaded"), - this, false); + mDocument->RemoveSystemEventListener(u"DOMContentLoaded"_ns, this, false); } } @@ -1505,7 +1504,7 @@ void FontFaceSet::DispatchLoadingEventAndReplaceReadyPromise() { return; } - (new AsyncEventDispatcher(this, NS_LITERAL_STRING("loading"), CanBubble::eNo)) + (new AsyncEventDispatcher(this, u"loading"_ns, CanBubble::eNo)) ->PostDOMEvent(); if (PrefEnabled()) { @@ -1636,12 +1635,10 @@ void FontFaceSet::CheckLoadingFinished() { } } - DispatchLoadingFinishedEvent(NS_LITERAL_STRING("loadingdone"), - std::move(loaded)); + DispatchLoadingFinishedEvent(u"loadingdone"_ns, std::move(loaded)); if (!failed.IsEmpty()) { - DispatchLoadingFinishedEvent(NS_LITERAL_STRING("loadingerror"), - std::move(failed)); + DispatchLoadingFinishedEvent(u"loadingerror"_ns, std::move(failed)); } } diff --git a/layout/style/FontPreloader.cpp b/layout/style/FontPreloader.cpp index 7dd414f2ec2f..09ccc8bb4f08 100644 --- a/layout/style/FontPreloader.cpp +++ b/layout/style/FontPreloader.cpp @@ -77,9 +77,9 @@ nsresult FontPreloader::BuildChannel( nsCOMPtr httpChannel(do_QueryInterface(channel)); if (httpChannel) { rv = httpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Accept"), - NS_LITERAL_CSTRING("application/font-woff2;q=1.0,application/" - "font-woff;q=0.9,*/*;q=0.8"), + "Accept"_ns, + nsLiteralCString("application/font-woff2;q=1.0,application/" + "font-woff;q=0.9,*/*;q=0.8"), false); NS_ENSURE_SUCCESS(rv, rv); @@ -91,9 +91,8 @@ nsresult FontPreloader::BuildChannel( // and apply additional compression at the content-encoding layer if (aFontFaceSrc->mFormatFlags & (gfxUserFontSet::FLAG_FORMAT_WOFF | gfxUserFontSet::FLAG_FORMAT_WOFF2)) { - rv = httpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Accept-Encoding"), - NS_LITERAL_CSTRING("identity"), false); + rv = httpChannel->SetRequestHeader("Accept-Encoding"_ns, "identity"_ns, + false); NS_ENSURE_SUCCESS(rv, rv); } } else { diff --git a/layout/style/GeckoBindings.cpp b/layout/style/GeckoBindings.cpp index 7bfa8f0de92b..146acc151e56 100644 --- a/layout/style/GeckoBindings.cpp +++ b/layout/style/GeckoBindings.cpp @@ -1449,7 +1449,7 @@ GeckoFontMetrics Gecko_GetFontMetrics(const nsPresContext* aPresContext, int32_t d2a = aPresContext->AppUnitsPerDevPixel(); auto ToLength = [](nscoord aLen) { - return Length::FromPixels(CSSPixel::FromAppUnits(aLen)); + return Length::FromPixels(CSSPixel::FromAppUnits(aLen)); }; return {ToLength(NS_round(metrics.xHeight * d2a)), ToLength(NS_round(metrics.zeroWidth * d2a))}; @@ -1506,7 +1506,7 @@ static already_AddRefed LoadImportSheet( // Make a dummy URI if we don't have one because some methods assume // non-null URIs. if (!uri) { - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("about:invalid")); + NS_NewURI(getter_AddRefs(uri), "about:invalid"_ns); } emptySheet->SetURIs(uri, uri, uri); emptySheet->SetPrincipal(aURL.ExtraData().Principal()); diff --git a/layout/style/GlobalStyleSheetCache.cpp b/layout/style/GlobalStyleSheetCache.cpp index f7ef6ee1ab4b..07df7092497f 100644 --- a/layout/style/GlobalStyleSheetCache.cpp +++ b/layout/style/GlobalStyleSheetCache.cpp @@ -393,19 +393,18 @@ void GlobalStyleSheetCache::InitSharedSheetsInParent() { // Normally calling ToShared on UA sheets should not fail. It happens // in practice in odd cases that seem like corrupted installations; see bug // 1621773. On failure, return early and fall back to non-shared sheets. -#define STYLE_SHEET(identifier_, url_, shared_) \ - if (shared_) { \ - StyleSheet* sheet = identifier_##Sheet(); \ - size_t i = size_t(UserAgentStyleSheetID::identifier_); \ - URLExtraData::sShared[i] = sheet->URLData(); \ - header->mSheets[i] = sheet->ToShared(builder.get(), message); \ - if (!header->mSheets[i]) { \ - CrashReporter::AppendAppNotesToCrashReport(NS_LITERAL_CSTRING("\n") + \ - message); \ - Telemetry::Accumulate( \ - Telemetry::SHARED_MEMORY_UA_SHEETS_TOSHMEM_SUCCEEDED, false); \ - return; \ - } \ +#define STYLE_SHEET(identifier_, url_, shared_) \ + if (shared_) { \ + StyleSheet* sheet = identifier_##Sheet(); \ + size_t i = size_t(UserAgentStyleSheetID::identifier_); \ + URLExtraData::sShared[i] = sheet->URLData(); \ + header->mSheets[i] = sheet->ToShared(builder.get(), message); \ + if (!header->mSheets[i]) { \ + CrashReporter::AppendAppNotesToCrashReport("\n"_ns + message); \ + Telemetry::Accumulate( \ + Telemetry::SHARED_MEMORY_UA_SHEETS_TOSHMEM_SUCCEEDED, false); \ + return; \ + } \ } #include "mozilla/UserAgentStyleSheetList.h" #undef STYLE_SHEET @@ -495,8 +494,8 @@ void GlobalStyleSheetCache::InitFromProfile() { contentFile->Clone(getter_AddRefs(chromeFile)); if (!chromeFile) return; - contentFile->Append(NS_LITERAL_STRING("userContent.css")); - chromeFile->Append(NS_LITERAL_STRING("userChrome.css")); + contentFile->Append(u"userContent.css"_ns); + chromeFile->Append(u"userChrome.css"_ns); mUserContentSheet = LoadSheetFile(contentFile, eUserSheetFeatures); mUserChromeSheet = LoadSheetFile(chromeFile, eUserSheetFeatures); diff --git a/layout/style/ImageLoader.cpp b/layout/style/ImageLoader.cpp index 5eafe2aaabff..01708395bb1a 100644 --- a/layout/style/ImageLoader.cpp +++ b/layout/style/ImageLoader.cpp @@ -414,8 +414,7 @@ already_AddRefed ImageLoader::LoadImage( RefPtr request; nsresult rv = nsContentUtils::LoadImage( uri, loadingDoc, loadingDoc, data.Principal(), 0, data.ReferrerInfo(), - sImageObserver, loadFlags, NS_LITERAL_STRING("css"), - getter_AddRefs(request)); + sImageObserver, loadFlags, u"css"_ns, getter_AddRefs(request)); if (NS_FAILED(rv) || !request) { return nullptr; diff --git a/layout/style/Loader.cpp b/layout/style/Loader.cpp index ddb975cbff1d..4778cab8209e 100644 --- a/layout/style/Loader.cpp +++ b/layout/style/Loader.cpp @@ -441,10 +441,9 @@ void SheetLoadData::FireLoadEvent(nsIThreadInternal* aThread) { nsCOMPtr node = mOwningNode; MOZ_ASSERT(node, "How did that happen???"); - nsContentUtils::DispatchTrustedEvent( - node->OwnerDoc(), node, - mLoadFailed ? NS_LITERAL_STRING("error") : NS_LITERAL_STRING("load"), - CanBubble::eNo, Cancelable::eNo); + nsContentUtils::DispatchTrustedEvent(node->OwnerDoc(), node, + mLoadFailed ? u"error"_ns : u"load"_ns, + CanBubble::eNo, Cancelable::eNo); // And unblock onload mLoader->UnblockOnload(true); @@ -786,7 +785,7 @@ nsresult SheetLoadData::VerifySheetReadyToParse(nsresult aStatus, nsCOMPtr referrer = ReferrerInfo()->GetOriginalReferrer(); nsContentUtils::ReportToConsole( - errorFlag, NS_LITERAL_CSTRING("CSS Loader"), mLoader->mDocument, + errorFlag, "CSS Loader"_ns, mLoader->mDocument, nsContentUtils::eCSS_PROPERTIES, errorMessage, strings, referrer); if (errorFlag == nsIScriptError::errorFlag) { @@ -895,9 +894,9 @@ nsresult Loader::CheckContentPolicy(nsIPrincipal* aLoadingPrincipal, } int16_t shouldLoad = nsIContentPolicy::ACCEPT; - nsresult rv = NS_CheckContentLoadPolicy( - aTargetURI, secCheckLoadInfo, NS_LITERAL_CSTRING("text/css"), &shouldLoad, - nsContentUtils::GetContentPolicy()); + nsresult rv = NS_CheckContentLoadPolicy(aTargetURI, secCheckLoadInfo, + "text/css"_ns, &shouldLoad, + nsContentUtils::GetContentPolicy()); if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) { return NS_ERROR_CONTENT_BLOCKED; } @@ -954,12 +953,11 @@ std::tuple, Loader::SheetState> Loader::CreateSheet( } if (mSheets) { - SheetLoadDataHashKey key(aURI, aTriggeringPrincipal, LoaderPrincipal(), - PartitionedPrincipal(), - GetFallbackEncoding(*this, aLinkingContent, - aPreloadOrParentDataEncoding), - aCORSMode, aParsingMode, mCompatMode, sriMetadata, - aIsPreload); + SheetLoadDataHashKey key( + aURI, aTriggeringPrincipal, LoaderPrincipal(), PartitionedPrincipal(), + GetFallbackEncoding(*this, aLinkingContent, + aPreloadOrParentDataEncoding), + aCORSMode, aParsingMode, mCompatMode, sriMetadata, aIsPreload); auto cacheResult = mSheets->Lookup(*this, key, aSyncLoad); if (const auto& [styleSheet, sheetState] = cacheResult; styleSheet) { LOG((" Hit cache with state: %s", gStateStrings[size_t(sheetState)])); @@ -1255,7 +1253,7 @@ nsresult Loader::LoadSheet(SheetLoadData& aLoadData, SheetState aSheetState, // Force UA sheets to be UTF-8. // XXX this is only necessary because the default in // SheetLoadData::OnDetermineCharset is wrong (bug 521039). - channel->SetContentCharset(NS_LITERAL_CSTRING("UTF-8")); + channel->SetContentCharset("UTF-8"_ns); // Manually feed the streamloader the contents of the stream. // This will call back into OnStreamComplete @@ -1399,7 +1397,7 @@ nsresult Loader::LoadSheet(SheetLoadData& aLoadData, SheetState aSheetState, if (nsCOMPtr timedChannel = do_QueryInterface(httpChannel)) { if (aLoadData.mParentData) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("css")); + timedChannel->SetInitiatorType(u"css"_ns); // This is a child sheet load. // @@ -1433,14 +1431,14 @@ nsresult Loader::LoadSheet(SheetLoadData& aLoadData, SheetState aSheetState, } } else { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("link")); + timedChannel->SetInitiatorType(u"link"_ns); } } } // Now tell the channel we expect text/css data back.... We do // this before opening it, so it's only treated as a hint. - channel->SetContentType(NS_LITERAL_CSTRING("text/css")); + channel->SetContentType("text/css"_ns); // We don't have to hold on to the stream loader. The ownership // model is: Necko owns the stream loader, which owns the load data, @@ -1770,9 +1768,9 @@ Result Loader::LoadStyleLink( if (aInfo.mContent && !mDocument->IsLoadedAsData()) { // Fire an async error event on it. RefPtr loadBlockingAsyncDispatcher = - new LoadBlockingAsyncEventDispatcher( - aInfo.mContent, NS_LITERAL_STRING("error"), CanBubble::eNo, - ChromeOnlyDispatch::eNo); + new LoadBlockingAsyncEventDispatcher(aInfo.mContent, u"error"_ns, + CanBubble::eNo, + ChromeOnlyDispatch::eNo); loadBlockingAsyncDispatcher->PostDOMEvent(); } return Err(rv); diff --git a/layout/style/MediaQueryList.cpp b/layout/style/MediaQueryList.cpp index 91400a33a58d..2d3228d4cf41 100644 --- a/layout/style/MediaQueryList.cpp +++ b/layout/style/MediaQueryList.cpp @@ -14,7 +14,7 @@ #include "nsPresContext.h" #include "mozilla/dom/Document.h" -#define ONCHANGE_STRING NS_LITERAL_STRING("change") +#define ONCHANGE_STRING u"change"_ns namespace mozilla { namespace dom { diff --git a/layout/style/StyleSheet.cpp b/layout/style/StyleSheet.cpp index 3873708ca0cc..328b1cbfddf2 100644 --- a/layout/style/StyleSheet.cpp +++ b/layout/style/StyleSheet.cpp @@ -1057,7 +1057,7 @@ void StyleSheet::List(FILE* aOut, int32_t aIndent) { rule->GetCssText(cssText); NS_ConvertUTF16toUTF8 s(cssText); - s.ReplaceSubstring(NS_LITERAL_CSTRING("\n"), newlineIndent); + s.ReplaceSubstring("\n"_ns, newlineIndent); fprintf_stderr(aOut, "%s\n", s.get()); } diff --git a/layout/style/nsCSSAnonBoxes.cpp b/layout/style/nsCSSAnonBoxes.cpp index 2b9b28dd598b..0d320532eb1c 100644 --- a/layout/style/nsCSSAnonBoxes.cpp +++ b/layout/style/nsCSSAnonBoxes.cpp @@ -17,8 +17,7 @@ using namespace mozilla; #ifdef MOZ_XUL /* static */ bool nsCSSAnonBoxes::IsTreePseudoElement(nsAtom* aPseudo) { - return StringBeginsWith(nsDependentAtomString(aPseudo), - NS_LITERAL_STRING(":-moz-tree-")); + return StringBeginsWith(nsDependentAtomString(aPseudo), u":-moz-tree-"_ns); } #endif diff --git a/layout/style/nsCSSProps.cpp b/layout/style/nsCSSProps.cpp index 72eeb81f4348..eb7ba6bbb466 100644 --- a/layout/style/nsCSSProps.cpp +++ b/layout/style/nsCSSProps.cpp @@ -138,7 +138,7 @@ void nsCSSProps::ReleaseTable(void) { /* static */ bool nsCSSProps::IsCustomPropertyName(const nsACString& aProperty) { return aProperty.Length() >= CSS_CUSTOM_NAME_PREFIX_LENGTH && - StringBeginsWith(aProperty, NS_LITERAL_CSTRING("--")); + StringBeginsWith(aProperty, "--"_ns); } nsCSSPropertyID nsCSSProps::LookupPropertyByIDLName( diff --git a/layout/style/nsCSSPseudoElements.cpp b/layout/style/nsCSSPseudoElements.cpp index be525eaa318d..dcb8ed34098d 100644 --- a/layout/style/nsCSSPseudoElements.cpp +++ b/layout/style/nsCSSPseudoElements.cpp @@ -116,11 +116,11 @@ bool nsCSSPseudoElements::PseudoElementSupportsUserActionState( nsString nsCSSPseudoElements::PseudoTypeAsString(Type aPseudoType) { switch (aPseudoType) { case PseudoStyleType::before: - return NS_LITERAL_STRING("::before"); + return u"::before"_ns; case PseudoStyleType::after: - return NS_LITERAL_STRING("::after"); + return u"::after"_ns; case PseudoStyleType::marker: - return NS_LITERAL_STRING("::marker"); + return u"::marker"_ns; default: MOZ_ASSERT(aPseudoType == PseudoStyleType::NotPseudo, "Unexpected pseudo type"); diff --git a/layout/style/nsComputedDOMStyle.cpp b/layout/style/nsComputedDOMStyle.cpp index 467fc6614e9e..27d31b1c8641 100644 --- a/layout/style/nsComputedDOMStyle.cpp +++ b/layout/style/nsComputedDOMStyle.cpp @@ -687,8 +687,7 @@ void nsComputedDOMStyle::GetCSSImageURLs(const nsACString& aPropertyName, if (prop == eCSSProperty_UNKNOWN) { // Note: not using nsPrintfCString here in case aPropertyName contains // nulls. - aRv.ThrowSyntaxError(NS_LITERAL_CSTRING("Invalid property name '") + - aPropertyName + NS_LITERAL_CSTRING("'")); + aRv.ThrowSyntaxError("Invalid property name '"_ns + aPropertyName + "'"_ns); return; } @@ -1118,9 +1117,9 @@ void nsComputedDOMStyle::RemoveProperty(const nsACString& aPropertyName, nsAString& aReturn, ErrorResult& aRv) { // Note: not using nsPrintfCString here in case aPropertyName contains // nulls. - aRv.ThrowNoModificationAllowedError( - NS_LITERAL_CSTRING("Can't remove property '") + aPropertyName + - NS_LITERAL_CSTRING("' from computed style")); + aRv.ThrowNoModificationAllowedError("Can't remove property '"_ns + + aPropertyName + + "' from computed style"_ns); } void nsComputedDOMStyle::GetPropertyPriority(const nsACString& aPropertyName, @@ -1135,9 +1134,8 @@ void nsComputedDOMStyle::SetProperty(const nsACString& aPropertyName, ErrorResult& aRv) { // Note: not using nsPrintfCString here in case aPropertyName contains // nulls. - aRv.ThrowNoModificationAllowedError( - NS_LITERAL_CSTRING("Can't set value for property '") + aPropertyName + - NS_LITERAL_CSTRING("' in computed style")); + aRv.ThrowNoModificationAllowedError("Can't set value for property '"_ns + + aPropertyName + "' in computed style"_ns); } void nsComputedDOMStyle::IndexedGetter(uint32_t aIndex, bool& aFound, @@ -1267,7 +1265,7 @@ already_AddRefed nsComputedDOMStyle::MatrixToCSSValue( const mozilla::gfx::Matrix4x4& matrix) { bool is3D = !matrix.Is2D(); - nsAutoString resultString(NS_LITERAL_STRING("matrix")); + nsAutoString resultString(u"matrix"_ns); if (is3D) { resultString.AppendLiteral("3d"); } diff --git a/layout/style/test/gtest/ImportScannerTest.cpp b/layout/style/test/gtest/ImportScannerTest.cpp index ef6b5a58392f..383090b524cc 100644 --- a/layout/style/test/gtest/ImportScannerTest.cpp +++ b/layout/style/test/gtest/ImportScannerTest.cpp @@ -28,9 +28,9 @@ TEST(ImportScanner, Simple) "@import \"bazz)\""); ASSERT_EQ(urls.Length(), 3u); - ASSERT_EQ(urls[0], NS_LITERAL_STRING("bar")); - ASSERT_EQ(urls[1], NS_LITERAL_STRING("baz")); - ASSERT_EQ(urls[2], NS_LITERAL_STRING("bazz)")); + ASSERT_EQ(urls[0], u"bar"_ns); + ASSERT_EQ(urls[1], u"baz"_ns); + ASSERT_EQ(urls[2], u"bazz)"_ns); } TEST(ImportScanner, UrlWithQuotes) @@ -44,9 +44,9 @@ TEST(ImportScanner, UrlWithQuotes) "@import\turL( 'bazz' ); "); ASSERT_EQ(urls.Length(), 3u); - ASSERT_EQ(urls[0], NS_LITERAL_STRING("bar")); - ASSERT_EQ(urls[1], NS_LITERAL_STRING("baz")); - ASSERT_EQ(urls[2], NS_LITERAL_STRING("bazz")); + ASSERT_EQ(urls[0], u"bar"_ns); + ASSERT_EQ(urls[1], u"baz"_ns); + ASSERT_EQ(urls[2], u"bazz"_ns); } TEST(ImportScanner, MediaIsIgnored) @@ -59,7 +59,7 @@ TEST(ImportScanner, MediaIsIgnored) "@import\turL( bazz ) (max-width: 100px);"); ASSERT_EQ(urls.Length(), 3u); - ASSERT_EQ(urls[0], NS_LITERAL_STRING("bar")); - ASSERT_EQ(urls[1], NS_LITERAL_STRING("baz")); - ASSERT_EQ(urls[2], NS_LITERAL_STRING("bazz")); + ASSERT_EQ(urls[0], u"bar"_ns); + ASSERT_EQ(urls[1], u"baz"_ns); + ASSERT_EQ(urls[2], u"bazz"_ns); } diff --git a/layout/style/test/gtest/StyloParsingBench.cpp b/layout/style/test/gtest/StyloParsingBench.cpp index a0b6ddeda074..a5ad55eb0c19 100644 --- a/layout/style/test/gtest/StyloParsingBench.cpp +++ b/layout/style/test/gtest/StyloParsingBench.cpp @@ -102,11 +102,11 @@ MOZ_GTEST_BENCH(Stylo, Servo_StyleSheet_FromUTF8Bytes_Bench_UseCounters, [] { }); MOZ_GTEST_BENCH(Stylo, Servo_DeclarationBlock_SetPropertyById_Bench, - [] { ServoSetPropertyByIdBench(NS_LITERAL_CSTRING("10px")); }); + [] { ServoSetPropertyByIdBench("10px"_ns); }); MOZ_GTEST_BENCH(Stylo, Servo_DeclarationBlock_SetPropertyById_WithInitialSpace_Bench, - [] { ServoSetPropertyByIdBench(NS_LITERAL_CSTRING(" 10px")); }); + [] { ServoSetPropertyByIdBench(" 10px"_ns); }); MOZ_GTEST_BENCH(Stylo, Servo_DeclarationBlock_GetPropertyById_Bench, ServoGetPropertyValueById); diff --git a/layout/svg/SVGAFrame.cpp b/layout/svg/SVGAFrame.cpp index 994a35472f0d..30a2604f6486 100644 --- a/layout/svg/SVGAFrame.cpp +++ b/layout/svg/SVGAFrame.cpp @@ -41,7 +41,7 @@ class SVGAFrame final : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGA"), aResult); + return MakeFrameName(u"SVGA"_ns, aResult); } #endif }; diff --git a/layout/svg/SVGContextPaint.cpp b/layout/svg/SVGContextPaint.cpp index 587702af8c19..32d97a3c0133 100644 --- a/layout/svg/SVGContextPaint.cpp +++ b/layout/svg/SVGContextPaint.cpp @@ -63,8 +63,8 @@ bool SVGContextPaint::IsAllowedForImageFromURI(nsIURI* aURI) { BasePrincipal::CreateContentPrincipal(aURI, OriginAttributes()); nsString addonId; if (NS_SUCCEEDED(principal->GetAddonId(addonId))) { - if (StringEndsWith(addonId, NS_LITERAL_STRING("@mozilla.org")) || - StringEndsWith(addonId, NS_LITERAL_STRING("@mozilla.com"))) { + if (StringEndsWith(addonId, u"@mozilla.org"_ns) || + StringEndsWith(addonId, u"@mozilla.com"_ns)) { return true; } } diff --git a/layout/svg/SVGFEContainerFrame.cpp b/layout/svg/SVGFEContainerFrame.cpp index 752cdb10a088..a8283b39ee58 100644 --- a/layout/svg/SVGFEContainerFrame.cpp +++ b/layout/svg/SVGFEContainerFrame.cpp @@ -47,7 +47,7 @@ class SVGFEContainerFrame final : public nsContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGFEContainer"), aResult); + return MakeFrameName(u"SVGFEContainer"_ns, aResult); } #endif diff --git a/layout/svg/SVGFEImageFrame.cpp b/layout/svg/SVGFEImageFrame.cpp index f80aeab584fe..6baf45d30713 100644 --- a/layout/svg/SVGFEImageFrame.cpp +++ b/layout/svg/SVGFEImageFrame.cpp @@ -56,7 +56,7 @@ class SVGFEImageFrame final : public nsFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGFEImage"), aResult); + return MakeFrameName(u"SVGFEImage"_ns, aResult); } #endif diff --git a/layout/svg/SVGFELeafFrame.cpp b/layout/svg/SVGFELeafFrame.cpp index bb705f8a2091..15689aea6764 100644 --- a/layout/svg/SVGFELeafFrame.cpp +++ b/layout/svg/SVGFELeafFrame.cpp @@ -49,7 +49,7 @@ class SVGFELeafFrame final : public nsFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGFELeaf"), aResult); + return MakeFrameName(u"SVGFELeaf"_ns, aResult); } #endif diff --git a/layout/svg/SVGFEUnstyledLeafFrame.cpp b/layout/svg/SVGFEUnstyledLeafFrame.cpp index ae222b46b594..c11934ae4615 100644 --- a/layout/svg/SVGFEUnstyledLeafFrame.cpp +++ b/layout/svg/SVGFEUnstyledLeafFrame.cpp @@ -44,7 +44,7 @@ class SVGFEUnstyledLeafFrame final : public nsFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGFEUnstyledLeaf"), aResult); + return MakeFrameName(u"SVGFEUnstyledLeaf"_ns, aResult); } #endif diff --git a/layout/svg/SVGForeignObjectFrame.h b/layout/svg/SVGForeignObjectFrame.h index 172b86a7fbee..0910389a1045 100644 --- a/layout/svg/SVGForeignObjectFrame.h +++ b/layout/svg/SVGForeignObjectFrame.h @@ -67,7 +67,7 @@ class SVGForeignObjectFrame final : public nsContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGForeignObject"), aResult); + return MakeFrameName(u"SVGForeignObject"_ns, aResult); } #endif diff --git a/layout/svg/SVGGFrame.h b/layout/svg/SVGGFrame.h index 4dc827337c3e..69b4a1da80c5 100644 --- a/layout/svg/SVGGFrame.h +++ b/layout/svg/SVGGFrame.h @@ -41,7 +41,7 @@ class SVGGFrame : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGG"), aResult); + return MakeFrameName(u"SVGG"_ns, aResult); } #endif diff --git a/layout/svg/SVGGenericContainerFrame.h b/layout/svg/SVGGenericContainerFrame.h index b58500b4cfe4..b7433da08628 100644 --- a/layout/svg/SVGGenericContainerFrame.h +++ b/layout/svg/SVGGenericContainerFrame.h @@ -44,7 +44,7 @@ class SVGGenericContainerFrame final : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGGenericContainer"), aResult); + return MakeFrameName(u"SVGGenericContainer"_ns, aResult); } #endif diff --git a/layout/svg/SVGGeometryFrame.h b/layout/svg/SVGGeometryFrame.h index 3d6b00ce0977..e45153910e6a 100644 --- a/layout/svg/SVGGeometryFrame.h +++ b/layout/svg/SVGGeometryFrame.h @@ -84,7 +84,7 @@ class SVGGeometryFrame : public nsFrame, public nsSVGDisplayableFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGGeometry"), aResult); + return MakeFrameName(u"SVGGeometry"_ns, aResult); } #endif diff --git a/layout/svg/SVGImageFrame.h b/layout/svg/SVGImageFrame.h index 586f76c2a077..627c81061383 100644 --- a/layout/svg/SVGImageFrame.h +++ b/layout/svg/SVGImageFrame.h @@ -87,7 +87,7 @@ class SVGImageFrame final : public SVGGeometryFrame, public nsIReflowCallback { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGImage"), aResult); + return MakeFrameName(u"SVGImage"_ns, aResult); } #endif diff --git a/layout/svg/SVGInnerSVGFrame.h b/layout/svg/SVGInnerSVGFrame.h index b8a67961aaf5..516019ab2c14 100644 --- a/layout/svg/SVGInnerSVGFrame.h +++ b/layout/svg/SVGInnerSVGFrame.h @@ -37,7 +37,7 @@ class SVGInnerSVGFrame final : public SVGViewportFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGInnerSVG"), aResult); + return MakeFrameName(u"SVGInnerSVG"_ns, aResult); } #endif }; diff --git a/layout/svg/SVGMarkerFrame.h b/layout/svg/SVGMarkerFrame.h index 68129b3669c1..d81a353a7e34 100644 --- a/layout/svg/SVGMarkerFrame.h +++ b/layout/svg/SVGMarkerFrame.h @@ -70,7 +70,7 @@ class SVGMarkerFrame final : public nsSVGContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGMarker"), aResult); + return MakeFrameName(u"SVGMarker"_ns, aResult); } #endif @@ -152,7 +152,7 @@ class SVGMarkerAnonChildFrame final : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGMarkerAnonChild"), aResult); + return MakeFrameName(u"SVGMarkerAnonChild"_ns, aResult); } #endif diff --git a/layout/svg/SVGMaskFrame.h b/layout/svg/SVGMaskFrame.h index ada38fb30dbd..048d8df3517c 100644 --- a/layout/svg/SVGMaskFrame.h +++ b/layout/svg/SVGMaskFrame.h @@ -87,7 +87,7 @@ class SVGMaskFrame final : public nsSVGContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGMask"), aResult); + return MakeFrameName(u"SVGMask"_ns, aResult); } #endif diff --git a/layout/svg/SVGObserverUtils.cpp b/layout/svg/SVGObserverUtils.cpp index 398096ff41d7..9d265a13dda7 100644 --- a/layout/svg/SVGObserverUtils.cpp +++ b/layout/svg/SVGObserverUtils.cpp @@ -1488,8 +1488,7 @@ Element* SVGObserverUtils::GetAndObserveBackgroundImage(nsIFrame* aFrame, MOZ_ASSERT(hashtable, "this property should only store non-null values"); } - nsAutoString elementId = - NS_LITERAL_STRING("#") + nsDependentAtomString(aHref); + nsAutoString elementId = u"#"_ns + nsDependentAtomString(aHref); nsCOMPtr targetURI; nsContentUtils::NewURIWithDocumentCharset( getter_AddRefs(targetURI), elementId, diff --git a/layout/svg/SVGSymbolFrame.h b/layout/svg/SVGSymbolFrame.h index ca87ed76c368..2448dc2bc582 100644 --- a/layout/svg/SVGSymbolFrame.h +++ b/layout/svg/SVGSymbolFrame.h @@ -37,7 +37,7 @@ class SVGSymbolFrame final : public SVGViewportFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGSymbol"), aResult); + return MakeFrameName(u"SVGSymbol"_ns, aResult); } #endif }; diff --git a/layout/svg/SVGTextFrame.h b/layout/svg/SVGTextFrame.h index 402358d9af2f..0aa05cfffaba 100644 --- a/layout/svg/SVGTextFrame.h +++ b/layout/svg/SVGTextFrame.h @@ -213,7 +213,7 @@ class SVGTextFrame final : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGText"), aResult); + return MakeFrameName(u"SVGText"_ns, aResult); } #endif diff --git a/layout/svg/SVGUseFrame.h b/layout/svg/SVGUseFrame.h index ebeb1c43b053..e32b3500e267 100644 --- a/layout/svg/SVGUseFrame.h +++ b/layout/svg/SVGUseFrame.h @@ -49,7 +49,7 @@ class SVGUseFrame final : public SVGGFrame { #ifdef DEBUG_FRAME_DUMP nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGUse"), aResult); + return MakeFrameName(u"SVGUse"_ns, aResult); } #endif diff --git a/layout/svg/SVGViewFrame.cpp b/layout/svg/SVGViewFrame.cpp index 30759287e033..1f1d0bef82e3 100644 --- a/layout/svg/SVGViewFrame.cpp +++ b/layout/svg/SVGViewFrame.cpp @@ -53,7 +53,7 @@ class SVGViewFrame final : public nsFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGView"), aResult); + return MakeFrameName(u"SVGView"_ns, aResult); } #endif diff --git a/layout/svg/nsSVGClipPathFrame.h b/layout/svg/nsSVGClipPathFrame.h index c86a53f3e818..8f06a424c980 100644 --- a/layout/svg/nsSVGClipPathFrame.h +++ b/layout/svg/nsSVGClipPathFrame.h @@ -123,7 +123,7 @@ class nsSVGClipPathFrame final : public nsSVGContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGClipPath"), aResult); + return MakeFrameName(u"SVGClipPath"_ns, aResult); } #endif diff --git a/layout/svg/nsSVGGradientFrame.h b/layout/svg/nsSVGGradientFrame.h index 9e181b0c0533..38e8a147e278 100644 --- a/layout/svg/nsSVGGradientFrame.h +++ b/layout/svg/nsSVGGradientFrame.h @@ -52,7 +52,7 @@ class nsSVGGradientFrame : public nsSVGPaintServerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGGradient"), aResult); + return MakeFrameName(u"SVGGradient"_ns, aResult); } #endif // DEBUG @@ -131,7 +131,7 @@ class nsSVGLinearGradientFrame final : public nsSVGGradientFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGLinearGradient"), aResult); + return MakeFrameName(u"SVGLinearGradient"_ns, aResult); } #endif // DEBUG @@ -171,7 +171,7 @@ class nsSVGRadialGradientFrame final : public nsSVGGradientFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGRadialGradient"), aResult); + return MakeFrameName(u"SVGRadialGradient"_ns, aResult); } #endif // DEBUG diff --git a/layout/svg/nsSVGOuterSVGFrame.h b/layout/svg/nsSVGOuterSVGFrame.h index bfcd381e0a46..bbff3b937e9c 100644 --- a/layout/svg/nsSVGOuterSVGFrame.h +++ b/layout/svg/nsSVGOuterSVGFrame.h @@ -81,7 +81,7 @@ class nsSVGOuterSVGFrame final : public nsSVGDisplayContainerFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGOuterSVG"), aResult); + return MakeFrameName(u"SVGOuterSVG"_ns, aResult); } #endif @@ -245,7 +245,7 @@ class nsSVGOuterSVGAnonChildFrame final : public nsSVGDisplayContainerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGOuterSVGAnonChild"), aResult); + return MakeFrameName(u"SVGOuterSVGAnonChild"_ns, aResult); } #endif diff --git a/layout/svg/nsSVGPatternFrame.h b/layout/svg/nsSVGPatternFrame.h index 1b0815c36012..b9af8cbc8b01 100644 --- a/layout/svg/nsSVGPatternFrame.h +++ b/layout/svg/nsSVGPatternFrame.h @@ -62,7 +62,7 @@ class nsSVGPatternFrame final : public nsSVGPaintServerFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGPattern"), aResult); + return MakeFrameName(u"SVGPattern"_ns, aResult); } #endif // DEBUG diff --git a/layout/svg/nsSVGStopFrame.cpp b/layout/svg/nsSVGStopFrame.cpp index 017ae5854c6f..4ed3784016c7 100644 --- a/layout/svg/nsSVGStopFrame.cpp +++ b/layout/svg/nsSVGStopFrame.cpp @@ -53,7 +53,7 @@ class nsSVGStopFrame : public nsFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGStop"), aResult); + return MakeFrameName(u"SVGStop"_ns, aResult); } #endif }; diff --git a/layout/svg/nsSVGSwitchFrame.cpp b/layout/svg/nsSVGSwitchFrame.cpp index 13f235482785..36beb036e42c 100644 --- a/layout/svg/nsSVGSwitchFrame.cpp +++ b/layout/svg/nsSVGSwitchFrame.cpp @@ -37,7 +37,7 @@ class nsSVGSwitchFrame final : public SVGGFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SVGSwitch"), aResult); + return MakeFrameName(u"SVGSwitch"_ns, aResult); } #endif diff --git a/layout/tables/nsTableCellFrame.cpp b/layout/tables/nsTableCellFrame.cpp index 99571b8eb110..10013e6e188b 100644 --- a/layout/tables/nsTableCellFrame.cpp +++ b/layout/tables/nsTableCellFrame.cpp @@ -1045,7 +1045,7 @@ void nsTableCellFrame::AppendDirectlyOwnedAnonBoxes( #ifdef DEBUG_FRAME_DUMP nsresult nsTableCellFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableCell"), aResult); + return MakeFrameName(u"TableCell"_ns, aResult); } #endif @@ -1067,7 +1067,7 @@ nsMargin nsBCTableCellFrame::GetUsedBorder() const { #ifdef DEBUG_FRAME_DUMP nsresult nsBCTableCellFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("BCTableCell"), aResult); + return MakeFrameName(u"BCTableCell"_ns, aResult); } #endif diff --git a/layout/tables/nsTableColFrame.cpp b/layout/tables/nsTableColFrame.cpp index 250d5e17584b..844a8c319027 100644 --- a/layout/tables/nsTableColFrame.cpp +++ b/layout/tables/nsTableColFrame.cpp @@ -180,7 +180,7 @@ nsTableColFrame* nsTableColFrame::GetNextCol() const { #ifdef DEBUG_FRAME_DUMP nsresult nsTableColFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableCol"), aResult); + return MakeFrameName(u"TableCol"_ns, aResult); } #endif diff --git a/layout/tables/nsTableColGroupFrame.cpp b/layout/tables/nsTableColGroupFrame.cpp index 1aff8aaa9950..8accadf4aefd 100644 --- a/layout/tables/nsTableColGroupFrame.cpp +++ b/layout/tables/nsTableColGroupFrame.cpp @@ -443,7 +443,7 @@ void nsTableColGroupFrame::InvalidateFrameWithRect(const nsRect& aRect, #ifdef DEBUG_FRAME_DUMP nsresult nsTableColGroupFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableColGroup"), aResult); + return MakeFrameName(u"TableColGroup"_ns, aResult); } void nsTableColGroupFrame::Dump(int32_t aIndent) { diff --git a/layout/tables/nsTableFrame.cpp b/layout/tables/nsTableFrame.cpp index f01e81ea13d2..102ddcebff17 100644 --- a/layout/tables/nsTableFrame.cpp +++ b/layout/tables/nsTableFrame.cpp @@ -251,9 +251,8 @@ void nsTableFrame::RegisterPositionedTablePart(nsIFrame* aFrame) { if (content && !presContext->HasWarnedAboutPositionedTableParts()) { presContext->SetHasWarnedAboutPositionedTableParts(); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Layout: Tables"), - content->OwnerDoc(), nsContentUtils::eLAYOUT_PROPERTIES, - "TablePartRelPosWarning"); + nsIScriptError::warningFlag, "Layout: Tables"_ns, content->OwnerDoc(), + nsContentUtils::eLAYOUT_PROPERTIES, "TablePartRelPosWarning"); } } @@ -3712,7 +3711,7 @@ bool nsTableFrame::IsAutoLayout() { #ifdef DEBUG_FRAME_DUMP nsresult nsTableFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Table"), aResult); + return MakeFrameName(u"Table"_ns, aResult); } #endif diff --git a/layout/tables/nsTableRowFrame.cpp b/layout/tables/nsTableRowFrame.cpp index 743a65cd46c4..8dc1285a595b 100644 --- a/layout/tables/nsTableRowFrame.cpp +++ b/layout/tables/nsTableRowFrame.cpp @@ -1395,6 +1395,6 @@ NS_IMPL_FRAMEARENA_HELPERS(nsTableRowFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsTableRowFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableRow"), aResult); + return MakeFrameName(u"TableRow"_ns, aResult); } #endif diff --git a/layout/tables/nsTableRowGroupFrame.cpp b/layout/tables/nsTableRowGroupFrame.cpp index 4ae6c6d99548..52502a7ed683 100644 --- a/layout/tables/nsTableRowGroupFrame.cpp +++ b/layout/tables/nsTableRowGroupFrame.cpp @@ -1651,7 +1651,7 @@ NS_IMPL_FRAMEARENA_HELPERS(nsTableRowGroupFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsTableRowGroupFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableRowGroup"), aResult); + return MakeFrameName(u"TableRowGroup"_ns, aResult); } #endif diff --git a/layout/tables/nsTableWrapperFrame.cpp b/layout/tables/nsTableWrapperFrame.cpp index 5ed0200a1265..9dd85a9adb88 100644 --- a/layout/tables/nsTableWrapperFrame.cpp +++ b/layout/tables/nsTableWrapperFrame.cpp @@ -1026,6 +1026,6 @@ NS_IMPL_FRAMEARENA_HELPERS(nsTableWrapperFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsTableWrapperFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("TableWrapper"), aResult); + return MakeFrameName(u"TableWrapper"_ns, aResult); } #endif diff --git a/layout/tools/layout-debug/src/nsLayoutDebugCLH.cpp b/layout/tools/layout-debug/src/nsLayoutDebugCLH.cpp index d898928fce8c..6f4772f014ad 100644 --- a/layout/tools/layout-debug/src/nsLayoutDebugCLH.cpp +++ b/layout/tools/layout-debug/src/nsLayoutDebugCLH.cpp @@ -71,8 +71,8 @@ static nsresult HandleFlagWithOptionalArgument(nsICommandLine* aCmdLine, nsresult rv; nsString s; - rv = HandleFlagWithOptionalArgument(aCmdLine, aName, NS_LITERAL_STRING("0"), - s, aFlagPresent); + rv = + HandleFlagWithOptionalArgument(aCmdLine, aName, u"0"_ns, s, aFlagPresent); NS_ENSURE_SUCCESS(rv, rv); if (!aFlagPresent) { @@ -104,25 +104,24 @@ nsLayoutDebugCLH::Handle(nsICommandLine* aCmdLine) { nsString profileFilename; bool paged = false; - rv = HandleFlagWithOptionalArgument( - aCmdLine, NS_LITERAL_STRING("layoutdebug"), - NS_LITERAL_STRING("about:blank"), url, flagPresent); + rv = HandleFlagWithOptionalArgument(aCmdLine, u"layoutdebug"_ns, + u"about:blank"_ns, url, flagPresent); NS_ENSURE_SUCCESS(rv, rv); if (!flagPresent) { return NS_OK; } - rv = HandleFlagWithOptionalArgument(aCmdLine, NS_LITERAL_STRING("autoclose"), - 0.0, delay, autoclose); + rv = HandleFlagWithOptionalArgument(aCmdLine, u"autoclose"_ns, 0.0, delay, + autoclose); NS_ENSURE_SUCCESS(rv, rv); - rv = HandleFlagWithOptionalArgument( - aCmdLine, NS_LITERAL_STRING("capture-profile"), - NS_LITERAL_STRING("profile.json"), profileFilename, captureProfile); + rv = HandleFlagWithOptionalArgument(aCmdLine, u"capture-profile"_ns, + u"profile.json"_ns, profileFilename, + captureProfile); NS_ENSURE_SUCCESS(rv, rv); - rv = aCmdLine->HandleFlag(NS_LITERAL_STRING("paged"), false, &paged); + rv = aCmdLine->HandleFlag(u"paged"_ns, false, &paged); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr argsArray = nsArray::Create(); @@ -157,7 +156,7 @@ nsLayoutDebugCLH::Handle(nsICommandLine* aCmdLine) { } if (paged) { - rv = AppendArg(argsArray, NS_LITERAL_STRING("paged")); + rv = AppendArg(argsArray, u"paged"_ns); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp b/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp index 4d479f6a4495..20c8307eaa4c 100644 --- a/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp +++ b/layout/tools/layout-debug/src/nsLayoutDebuggingTools.cpp @@ -130,13 +130,13 @@ nsLayoutDebuggingTools::SetPagedMode(bool aPagedMode) { nsIntMargin unwriteableMargin(0, 0, 0, 0); printSettings->SetUnwriteableMarginInTwips(unwriteableMargin); - printSettings->SetHeaderStrLeft(NS_LITERAL_STRING("")); - printSettings->SetHeaderStrCenter(NS_LITERAL_STRING("")); - printSettings->SetHeaderStrRight(NS_LITERAL_STRING("")); + printSettings->SetHeaderStrLeft(u""_ns); + printSettings->SetHeaderStrCenter(u""_ns); + printSettings->SetHeaderStrRight(u""_ns); - printSettings->SetFooterStrLeft(NS_LITERAL_STRING("")); - printSettings->SetFooterStrCenter(NS_LITERAL_STRING("")); - printSettings->SetFooterStrRight(NS_LITERAL_STRING("")); + printSettings->SetFooterStrLeft(u""_ns); + printSettings->SetFooterStrCenter(u""_ns); + printSettings->SetFooterStrRight(u""_ns); nsCOMPtr contentViewer(doc_viewer(mDocShell)); contentViewer->SetPageModeForTesting(aPagedMode, printSettings); diff --git a/layout/xul/grid/nsGridRowGroupFrame.h b/layout/xul/grid/nsGridRowGroupFrame.h index d043c607d794..e7e625a7c0fa 100644 --- a/layout/xul/grid/nsGridRowGroupFrame.h +++ b/layout/xul/grid/nsGridRowGroupFrame.h @@ -30,7 +30,7 @@ class nsGridRowGroupFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("nsGridRowGroup"), aResult); + return MakeFrameName(u"nsGridRowGroup"_ns, aResult); } #endif diff --git a/layout/xul/grid/nsGridRowLeafFrame.h b/layout/xul/grid/nsGridRowLeafFrame.h index 56f0f9f52586..ce34f5b67cbc 100644 --- a/layout/xul/grid/nsGridRowLeafFrame.h +++ b/layout/xul/grid/nsGridRowLeafFrame.h @@ -38,7 +38,7 @@ class nsGridRowLeafFrame : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("nsGridRowLeaf"), aResult); + return MakeFrameName(u"nsGridRowLeaf"_ns, aResult); } #endif diff --git a/layout/xul/nsBoxFrame.cpp b/layout/xul/nsBoxFrame.cpp index 027216ecec17..cdc4f49f1999 100644 --- a/layout/xul/nsBoxFrame.cpp +++ b/layout/xul/nsBoxFrame.cpp @@ -983,7 +983,7 @@ void nsBoxFrame::BuildDisplayListForChildren(nsDisplayListBuilder* aBuilder, #ifdef DEBUG_FRAME_DUMP nsresult nsBoxFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("Box"), aResult); + return MakeFrameName(u"Box"_ns, aResult); } #endif diff --git a/layout/xul/nsButtonBoxFrame.cpp b/layout/xul/nsButtonBoxFrame.cpp index 0f788b74fd96..9257704fe452 100644 --- a/layout/xul/nsButtonBoxFrame.cpp +++ b/layout/xul/nsButtonBoxFrame.cpp @@ -68,14 +68,12 @@ void nsButtonBoxFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, mButtonBoxListener = new nsButtonBoxListener(this); - mContent->AddSystemEventListener(NS_LITERAL_STRING("blur"), - mButtonBoxListener, false); + mContent->AddSystemEventListener(u"blur"_ns, mButtonBoxListener, false); } void nsButtonBoxFrame::DestroyFrom(nsIFrame* aDestructRoot, PostDestroyData& aPostDestroyData) { - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("blur"), - mButtonBoxListener, false); + mContent->RemoveSystemEventListener(u"blur"_ns, mButtonBoxListener, false); mButtonBoxListener->mButtonBoxFrame = nullptr; mButtonBoxListener = nullptr; diff --git a/layout/xul/nsButtonBoxFrame.h b/layout/xul/nsButtonBoxFrame.h index d3613a617688..2d3ef5491421 100644 --- a/layout/xul/nsButtonBoxFrame.h +++ b/layout/xul/nsButtonBoxFrame.h @@ -42,7 +42,7 @@ class nsButtonBoxFrame : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("ButtonBoxFrame"), aResult); + return MakeFrameName(u"ButtonBoxFrame"_ns, aResult); } #endif diff --git a/layout/xul/nsDeckFrame.h b/layout/xul/nsDeckFrame.h index 6f6c53dcdc62..8eba9f62389b 100644 --- a/layout/xul/nsDeckFrame.h +++ b/layout/xul/nsDeckFrame.h @@ -48,7 +48,7 @@ class nsDeckFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Deck"), aResult); + return MakeFrameName(u"Deck"_ns, aResult); } #endif diff --git a/layout/xul/nsDocElementBoxFrame.cpp b/layout/xul/nsDocElementBoxFrame.cpp index c7faaf9559a8..2121a693ef6c 100644 --- a/layout/xul/nsDocElementBoxFrame.cpp +++ b/layout/xul/nsDocElementBoxFrame.cpp @@ -111,8 +111,8 @@ nsresult nsDocElementBoxFrame::CreateAnonymousContent( dom::NOT_FROM_PARSER); NS_ENSURE_SUCCESS(rv, rv); - mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::_default, - NS_LITERAL_STRING("true"), false); + mTooltipContent->SetAttr(kNameSpaceID_None, nsGkAtoms::_default, u"true"_ns, + false); // XXX(Bug 1631371) Check if this should use a fallible operation as it // pretended earlier. @@ -138,6 +138,6 @@ NS_QUERYFRAME_TAIL_INHERITING(nsBoxFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsDocElementBoxFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("DocElementBox"), aResult); + return MakeFrameName(u"DocElementBox"_ns, aResult); } #endif diff --git a/layout/xul/nsImageBoxFrame.cpp b/layout/xul/nsImageBoxFrame.cpp index cc1c5f953fe5..1829efa3a444 100644 --- a/layout/xul/nsImageBoxFrame.cpp +++ b/layout/xul/nsImageBoxFrame.cpp @@ -750,7 +750,7 @@ nscoord nsImageBoxFrame::GetXULBoxAscent(nsBoxLayoutState& aState) { #ifdef DEBUG_FRAME_DUMP nsresult nsImageBoxFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("ImageBox"), aResult); + return MakeFrameName(u"ImageBox"_ns, aResult); } #endif diff --git a/layout/xul/nsLeafBoxFrame.cpp b/layout/xul/nsLeafBoxFrame.cpp index 59c77eee2426..f015a2c7ae59 100644 --- a/layout/xul/nsLeafBoxFrame.cpp +++ b/layout/xul/nsLeafBoxFrame.cpp @@ -269,7 +269,7 @@ void nsLeafBoxFrame::Reflow(nsPresContext* aPresContext, #ifdef DEBUG_FRAME_DUMP nsresult nsLeafBoxFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("LeafBox"), aResult); + return MakeFrameName(u"LeafBox"_ns, aResult); } #endif diff --git a/layout/xul/nsMenuBarFrame.h b/layout/xul/nsMenuBarFrame.h index c4cefd249e44..21d7e89f2041 100644 --- a/layout/xul/nsMenuBarFrame.h +++ b/layout/xul/nsMenuBarFrame.h @@ -106,7 +106,7 @@ class nsMenuBarFrame final : public nsBoxFrame, public nsMenuParent { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("MenuBar"), aResult); + return MakeFrameName(u"MenuBar"_ns, aResult); } #endif diff --git a/layout/xul/nsMenuBarListener.cpp b/layout/xul/nsMenuBarListener.cpp index 1bbb54051780..efad6bf5439c 100644 --- a/layout/xul/nsMenuBarListener.cpp +++ b/layout/xul/nsMenuBarListener.cpp @@ -55,33 +55,28 @@ nsMenuBarListener::nsMenuBarListener(nsMenuBarFrame* aMenuBarFrame, // Also hook up the listener to the window listening for focus events. This // is so we can keep proper state as the user alt-tabs through processes. - mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("keypress"), this, - false); - mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("keydown"), this, - false); - mEventTarget->AddSystemEventListener(NS_LITERAL_STRING("keyup"), this, false); - mEventTarget->AddSystemEventListener( - NS_LITERAL_STRING("mozaccesskeynotfound"), this, false); + mEventTarget->AddSystemEventListener(u"keypress"_ns, this, false); + mEventTarget->AddSystemEventListener(u"keydown"_ns, this, false); + mEventTarget->AddSystemEventListener(u"keyup"_ns, this, false); + mEventTarget->AddSystemEventListener(u"mozaccesskeynotfound"_ns, this, false); // Need a capturing event listener if the user has blocked pages from // overriding system keys so that we can prevent menu accesskeys from being // cancelled. - mEventTarget->AddEventListener(NS_LITERAL_STRING("keydown"), this, true); + mEventTarget->AddEventListener(u"keydown"_ns, this, true); // mousedown event should be handled in all phase - mEventTarget->AddEventListener(NS_LITERAL_STRING("mousedown"), this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("mousedown"), this, false); - mEventTarget->AddEventListener(NS_LITERAL_STRING("blur"), this, true); + mEventTarget->AddEventListener(u"mousedown"_ns, this, true); + mEventTarget->AddEventListener(u"mousedown"_ns, this, false); + mEventTarget->AddEventListener(u"blur"_ns, this, true); - mEventTarget->AddEventListener(NS_LITERAL_STRING("MozDOMFullscreen:Entered"), - this, false); + mEventTarget->AddEventListener(u"MozDOMFullscreen:Entered"_ns, this, false); // Needs to listen to the deactivate event of the window. RefPtr topWindowEventTarget = nsContentUtils::GetWindowRoot(aMenuBarContent->GetComposedDoc()); mTopWindowEventTarget = topWindowEventTarget.get(); - mTopWindowEventTarget->AddSystemEventListener(NS_LITERAL_STRING("deactivate"), - this, true); + mTopWindowEventTarget->AddSystemEventListener(u"deactivate"_ns, this, true); } //////////////////////////////////////////////////////////////////////// @@ -91,26 +86,22 @@ nsMenuBarListener::~nsMenuBarListener() { } void nsMenuBarListener::OnDestroyMenuBarFrame() { - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("keypress"), this, + mEventTarget->RemoveSystemEventListener(u"keypress"_ns, this, false); + mEventTarget->RemoveSystemEventListener(u"keydown"_ns, this, false); + mEventTarget->RemoveSystemEventListener(u"keyup"_ns, this, false); + mEventTarget->RemoveSystemEventListener(u"mozaccesskeynotfound"_ns, this, false); - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), this, - false); - mEventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("keyup"), this, - false); - mEventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("mozaccesskeynotfound"), this, false); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, true); + mEventTarget->RemoveEventListener(u"keydown"_ns, this, true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, true); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("mousedown"), this, - false); - mEventTarget->RemoveEventListener(NS_LITERAL_STRING("blur"), this, true); + mEventTarget->RemoveEventListener(u"mousedown"_ns, this, true); + mEventTarget->RemoveEventListener(u"mousedown"_ns, this, false); + mEventTarget->RemoveEventListener(u"blur"_ns, this, true); - mEventTarget->RemoveEventListener( - NS_LITERAL_STRING("MozDOMFullscreen:Entered"), this, false); + mEventTarget->RemoveEventListener(u"MozDOMFullscreen:Entered"_ns, this, + false); - mTopWindowEventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("deactivate"), this, true); + mTopWindowEventTarget->RemoveSystemEventListener(u"deactivate"_ns, this, + true); mMenuBarFrame = nullptr; mEventTarget = nullptr; diff --git a/layout/xul/nsMenuFrame.cpp b/layout/xul/nsMenuFrame.cpp index ca15f04db412..b0c8ea33fb6b 100644 --- a/layout/xul/nsMenuFrame.cpp +++ b/layout/xul/nsMenuFrame.cpp @@ -75,8 +75,8 @@ class nsMenuActivateEvent : public Runnable { if (mIsActivate) { // Highlight the menu. - mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::menuactive, - NS_LITERAL_STRING("true"), true); + mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::menuactive, u"true"_ns, + true); // The menuactivated event is used by accessibility to track the user's // movements through menus domEventToFire.AssignLiteral("DOMMenuItemActive"); @@ -511,8 +511,8 @@ void nsMenuFrame::PopupOpened() { gMenuJustOpenedOrClosed = true; AutoWeakFrame weakFrame(this); - mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, - NS_LITERAL_STRING("true"), true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"true"_ns, + true); if (!weakFrame.IsAlive()) return; nsMenuParent* menuParent = GetMenuParent(); @@ -761,7 +761,7 @@ nsresult nsMenuFrame::Notify(nsITimer* aTimer) { // menu. AutoWeakFrame weakFrame(this); mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::menuactive, - NS_LITERAL_STRING("true"), true); + u"true"_ns, true); if (weakFrame.IsAlive()) { aTimer->InitWithCallback(mTimerMediator, kBlinkDelay, nsITimer::TYPE_ONE_SHOT); diff --git a/layout/xul/nsMenuFrame.h b/layout/xul/nsMenuFrame.h index c1b20e04a221..5c89d43bb148 100644 --- a/layout/xul/nsMenuFrame.h +++ b/layout/xul/nsMenuFrame.h @@ -190,7 +190,7 @@ class nsMenuFrame final : public nsBoxFrame, public nsIReflowCallback { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Menu"), aResult); + return MakeFrameName(u"Menu"_ns, aResult); } #endif diff --git a/layout/xul/nsMenuPopupFrame.cpp b/layout/xul/nsMenuPopupFrame.cpp index ace8b238f876..71b2c536ff8e 100644 --- a/layout/xul/nsMenuPopupFrame.cpp +++ b/layout/xul/nsMenuPopupFrame.cpp @@ -403,8 +403,7 @@ NS_IMETHODIMP nsXULPopupShownEvent::HandleEvent(Event* aEvent) { } void nsXULPopupShownEvent::CancelListener() { - mPopup->RemoveSystemEventListener(NS_LITERAL_STRING("transitionend"), this, - false); + mPopup->RemoveSystemEventListener(u"transitionend"_ns, this, false); } NS_IMPL_ISUPPORTS_INHERITED(nsXULPopupShownEvent, Runnable, @@ -626,7 +625,7 @@ void nsMenuPopupFrame::LayoutPopup(nsBoxLayoutState& aState, AnimationUtils::HasCurrentTransitions(mContent->AsElement(), PseudoStyleType::NotPseudo)) { mPopupShownDispatcher = new nsXULPopupShownEvent(mContent, pc); - mContent->AddSystemEventListener(NS_LITERAL_STRING("transitionend"), + mContent->AddSystemEventListener(u"transitionend"_ns, mPopupShownDispatcher, false, false); return; } @@ -976,7 +975,7 @@ void nsMenuPopupFrame::HidePopup(bool aDeselectMenu, nsPopupState aNewState) { nsViewManager* viewManager = view->GetViewManager(); viewManager->SetViewVisibility(view, nsViewVisibility_kHide); - FireDOMEvent(NS_LITERAL_STRING("DOMMenuInactive"), mContent); + FireDOMEvent(u"DOMMenuInactive"_ns, mContent); // XXX, bug 137033, In Windows, if mouse is outside the window when the // menupopup closes, no mouse_enter/mouse_exit event will be fired to clear diff --git a/layout/xul/nsMenuPopupFrame.h b/layout/xul/nsMenuPopupFrame.h index dfd4af5ffba1..97db15339820 100644 --- a/layout/xul/nsMenuPopupFrame.h +++ b/layout/xul/nsMenuPopupFrame.h @@ -341,7 +341,7 @@ class nsMenuPopupFrame final : public nsBoxFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("MenuPopup"), aResult); + return MakeFrameName(u"MenuPopup"_ns, aResult); } #endif diff --git a/layout/xul/nsPopupSetFrame.h b/layout/xul/nsPopupSetFrame.h index 561707ee7fbf..acc7bcc39e9f 100644 --- a/layout/xul/nsPopupSetFrame.h +++ b/layout/xul/nsPopupSetFrame.h @@ -50,7 +50,7 @@ class nsPopupSetFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("PopupSet"), aResult); + return MakeFrameName(u"PopupSet"_ns, aResult); } #endif diff --git a/layout/xul/nsResizerFrame.cpp b/layout/xul/nsResizerFrame.cpp index bf885b3347dd..0e992e649bc8 100644 --- a/layout/xul/nsResizerFrame.cpp +++ b/layout/xul/nsResizerFrame.cpp @@ -429,10 +429,8 @@ void nsResizerFrame::ResizeContent(nsIContent* aContent, nsICSSDeclaration* decl = inlineStyleContent->Style(); if (aOriginalSizeInfo) { - decl->GetPropertyValue(NS_LITERAL_CSTRING("width"), - aOriginalSizeInfo->width); - decl->GetPropertyValue(NS_LITERAL_CSTRING("height"), - aOriginalSizeInfo->height); + decl->GetPropertyValue("width"_ns, aOriginalSizeInfo->width); + decl->GetPropertyValue("height"_ns, aOriginalSizeInfo->height); } // only set the property if the element could have changed in that @@ -442,8 +440,7 @@ void nsResizerFrame::ResizeContent(nsIContent* aContent, if (!widthstr.IsEmpty() && !Substring(widthstr, widthstr.Length() - 2, 2).EqualsLiteral("px")) widthstr.AppendLiteral("px"); - decl->SetProperty(NS_LITERAL_CSTRING("width"), widthstr, EmptyString(), - IgnoreErrors()); + decl->SetProperty("width"_ns, widthstr, EmptyString(), IgnoreErrors()); } if (aDirection.mVertical) { NS_ConvertUTF16toUTF8 heightstr(aSizeInfo.height); @@ -451,8 +448,8 @@ void nsResizerFrame::ResizeContent(nsIContent* aContent, !Substring(heightstr, heightstr.Length() - 2, 2) .EqualsLiteral("px")) heightstr.AppendLiteral("px"); - decl->SetProperty(NS_LITERAL_CSTRING("height"), heightstr, - EmptyString(), IgnoreErrors()); + decl->SetProperty("height"_ns, heightstr, EmptyString(), + IgnoreErrors()); } } } diff --git a/layout/xul/nsRootBoxFrame.cpp b/layout/xul/nsRootBoxFrame.cpp index 4dc17674f318..cda25794ea56 100644 --- a/layout/xul/nsRootBoxFrame.cpp +++ b/layout/xul/nsRootBoxFrame.cpp @@ -222,6 +222,6 @@ NS_QUERYFRAME_TAIL_INHERITING(nsBoxFrame) #ifdef DEBUG_FRAME_DUMP nsresult nsRootBoxFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("RootBox"), aResult); + return MakeFrameName(u"RootBox"_ns, aResult); } #endif diff --git a/layout/xul/nsScrollbarButtonFrame.cpp b/layout/xul/nsScrollbarButtonFrame.cpp index 8eea8fdf8238..e6844bba2a59 100644 --- a/layout/xul/nsScrollbarButtonFrame.cpp +++ b/layout/xul/nsScrollbarButtonFrame.cpp @@ -125,7 +125,7 @@ bool nsScrollbarButtonFrame::HandleButtonPress(nsPresContext* aPresContext, // set this attribute so we can style it later AutoWeakFrame weakFrame(this); mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::active, - NS_LITERAL_STRING("true"), true); + u"true"_ns, true); PresShell::SetCapturingContent(mContent, CaptureFlags::IgnoreAllowedState); diff --git a/layout/xul/nsScrollbarButtonFrame.h b/layout/xul/nsScrollbarButtonFrame.h index aa30aeca4299..51f1fbd37b27 100644 --- a/layout/xul/nsScrollbarButtonFrame.h +++ b/layout/xul/nsScrollbarButtonFrame.h @@ -71,9 +71,8 @@ class nsScrollbarButtonFrame final : public nsButtonBoxFrame { protected: void StartRepeat() { - nsRepeatService::GetInstance()->Start( - Notify, this, mContent->OwnerDoc(), - NS_LITERAL_CSTRING("nsScrollbarButtonFrame")); + nsRepeatService::GetInstance()->Start(Notify, this, mContent->OwnerDoc(), + "nsScrollbarButtonFrame"_ns); } void StopRepeat() { nsRepeatService::GetInstance()->Stop(Notify, this); } void Notify(); diff --git a/layout/xul/nsScrollbarFrame.cpp b/layout/xul/nsScrollbarFrame.cpp index ce9788f9d4c3..16fd72461042 100644 --- a/layout/xul/nsScrollbarFrame.cpp +++ b/layout/xul/nsScrollbarFrame.cpp @@ -261,8 +261,7 @@ int32_t nsScrollbarFrame::MoveToNewPosition() { AutoWeakFrame weakFrame(this); if (mSmoothScroll) { - content->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth, - NS_LITERAL_STRING("true"), false); + content->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth, u"true"_ns, false); } content->SetAttr(kNameSpaceID_None, nsGkAtoms::curpos, curposStr, false); // notify the nsScrollbarFrame of the change @@ -297,18 +296,18 @@ static already_AddRefed MakeScrollbarButton( static constexpr nsLiteralString kSbattrValues[2][2] = { { - NS_LITERAL_STRING("scrollbar-up-top"), - NS_LITERAL_STRING("scrollbar-up-bottom"), + u"scrollbar-up-top"_ns, + u"scrollbar-up-bottom"_ns, }, { - NS_LITERAL_STRING("scrollbar-down-top"), - NS_LITERAL_STRING("scrollbar-down-bottom"), + u"scrollbar-down-top"_ns, + u"scrollbar-down-bottom"_ns, }, }; static constexpr nsLiteralString kTypeValues[2] = { - NS_LITERAL_STRING("decrement"), - NS_LITERAL_STRING("increment"), + u"decrement"_ns, + u"increment"_ns, }; aKey = AnonymousContentKey::Type_ScrollbarButton; @@ -377,8 +376,7 @@ nsresult nsScrollbarFrame::CreateAnonymousContent( nodeInfoManager->GetNodeInfo(nsGkAtoms::slider, nullptr, kNameSpaceID_XUL, nsINode::ELEMENT_NODE)); mSlider->SetAttr(kNameSpaceID_None, nsGkAtoms::orient, orient, false); - mSlider->SetAttr(kNameSpaceID_None, nsGkAtoms::flex, NS_LITERAL_STRING("1"), - false); + mSlider->SetAttr(kNameSpaceID_None, nsGkAtoms::flex, u"1"_ns, false); aElements.AppendElement(ContentInfo(mSlider, key)); diff --git a/layout/xul/nsScrollbarFrame.h b/layout/xul/nsScrollbarFrame.h index 15b0bb4eb631..b31ff9eac430 100644 --- a/layout/xul/nsScrollbarFrame.h +++ b/layout/xul/nsScrollbarFrame.h @@ -49,7 +49,7 @@ class nsScrollbarFrame final : public nsBoxFrame, #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("ScrollbarFrame"), aResult); + return MakeFrameName(u"ScrollbarFrame"_ns, aResult); } #endif diff --git a/layout/xul/nsSliderFrame.cpp b/layout/xul/nsSliderFrame.cpp index eabda43129db..7cb75a48739e 100644 --- a/layout/xul/nsSliderFrame.cpp +++ b/layout/xul/nsSliderFrame.cpp @@ -596,8 +596,7 @@ nsresult nsSliderFrame::HandleEvent(nsPresContext* aPresContext, #ifdef MOZ_WIDGET_GTK RefPtr thumb = thumbFrame->GetContent()->AsElement(); - thumb->SetAttr(kNameSpaceID_None, nsGkAtoms::active, - NS_LITERAL_STRING("true"), true); + thumb->SetAttr(kNameSpaceID_None, nsGkAtoms::active, u"true"_ns, true); #endif if (aEvent->mClass == eTouchEventClass) { @@ -773,8 +772,8 @@ static void UpdateAttribute(dom::Element* aScrollbar, nscoord aNewPos, str.AppendInt(aNewPos); if (aIsSmooth) { - aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth, - NS_LITERAL_STRING("true"), false); + aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::smooth, u"true"_ns, + false); } aScrollbar->SetAttr(kNameSpaceID_None, nsGkAtoms::curpos, str, aNotify); if (aIsSmooth) { @@ -1084,8 +1083,7 @@ nsresult nsSliderFrame::StartDrag(Event* aEvent) { #ifdef MOZ_WIDGET_GTK RefPtr thumb = thumbFrame->GetContent()->AsElement(); - thumb->SetAttr(kNameSpaceID_None, nsGkAtoms::active, - NS_LITERAL_STRING("true"), true); + thumb->SetAttr(kNameSpaceID_None, nsGkAtoms::active, u"true"_ns, true); #endif if (isHorizontal) @@ -1156,10 +1154,10 @@ void nsSliderFrame::AddListener() { if (!thumbFrame) { return; } - thumbFrame->GetContent()->AddSystemEventListener( - NS_LITERAL_STRING("mousedown"), mMediator, false, false); - thumbFrame->GetContent()->AddSystemEventListener( - NS_LITERAL_STRING("touchstart"), mMediator, false, false); + thumbFrame->GetContent()->AddSystemEventListener(u"mousedown"_ns, mMediator, + false, false); + thumbFrame->GetContent()->AddSystemEventListener(u"touchstart"_ns, mMediator, + false, false); } void nsSliderFrame::RemoveListener() { @@ -1168,10 +1166,10 @@ void nsSliderFrame::RemoveListener() { nsIFrame* thumbFrame = mFrames.FirstChild(); if (!thumbFrame) return; - thumbFrame->GetContent()->RemoveSystemEventListener( - NS_LITERAL_STRING("mousedown"), mMediator, false); - thumbFrame->GetContent()->RemoveSystemEventListener( - NS_LITERAL_STRING("touchstart"), mMediator, false); + thumbFrame->GetContent()->RemoveSystemEventListener(u"mousedown"_ns, + mMediator, false); + thumbFrame->GetContent()->RemoveSystemEventListener(u"touchstart"_ns, + mMediator, false); } bool nsSliderFrame::ShouldScrollForEvent(WidgetGUIEvent* aEvent) { diff --git a/layout/xul/nsSliderFrame.h b/layout/xul/nsSliderFrame.h index 7be9e8006a18..3f2dbe531e9e 100644 --- a/layout/xul/nsSliderFrame.h +++ b/layout/xul/nsSliderFrame.h @@ -53,7 +53,7 @@ class nsSliderFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SliderFrame"), aResult); + return MakeFrameName(u"SliderFrame"_ns, aResult); } #endif @@ -173,7 +173,7 @@ class nsSliderFrame final : public nsBoxFrame { void StartRepeat() { nsRepeatService::GetInstance()->Start(Notify, this, mContent->OwnerDoc(), - NS_LITERAL_CSTRING("nsSliderFrame")); + "nsSliderFrame"_ns); } void StopRepeat() { nsRepeatService::GetInstance()->Stop(Notify, this); } void Notify(); diff --git a/layout/xul/nsSplitterFrame.cpp b/layout/xul/nsSplitterFrame.cpp index 189aa02992a4..9d006baf845d 100644 --- a/layout/xul/nsSplitterFrame.cpp +++ b/layout/xul/nsSplitterFrame.cpp @@ -247,7 +247,7 @@ void nsSplitterFrame::Init(nsIContent* aContent, nsContainerFrame* aParent, if (!nsContentUtils::HasNonEmptyAttr(aContent, kNameSpaceID_None, nsGkAtoms::orient)) { aContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::orient, - NS_LITERAL_STRING("vertical"), false); + u"vertical"_ns, false); } } } @@ -443,20 +443,20 @@ void nsSplitterFrameInner::MouseDrag(nsPresContext* aPresContext, // printf("Collapse right\n"); if (supportsAfter) { RefPtr outer = mOuter->mContent->AsElement(); - outer->SetAttr(kNameSpaceID_None, nsGkAtoms::substate, - NS_LITERAL_STRING("after"), true); - outer->SetAttr(kNameSpaceID_None, nsGkAtoms::state, - NS_LITERAL_STRING("collapsed"), true); + outer->SetAttr(kNameSpaceID_None, nsGkAtoms::substate, u"after"_ns, + true); + outer->SetAttr(kNameSpaceID_None, nsGkAtoms::state, u"collapsed"_ns, + true); } } else if (pastBegin) { // printf("Collapse left\n"); if (supportsBefore) { RefPtr outer = mOuter->mContent->AsElement(); - outer->SetAttr(kNameSpaceID_None, nsGkAtoms::substate, - NS_LITERAL_STRING("before"), true); - outer->SetAttr(kNameSpaceID_None, nsGkAtoms::state, - NS_LITERAL_STRING("collapsed"), true); + outer->SetAttr(kNameSpaceID_None, nsGkAtoms::substate, u"before"_ns, + true); + outer->SetAttr(kNameSpaceID_None, nsGkAtoms::state, u"collapsed"_ns, + true); } } } @@ -465,8 +465,7 @@ void nsSplitterFrameInner::MouseDrag(nsPresContext* aPresContext, // we are dragging. if (currentState != Dragging) { mOuter->mContent->AsElement()->SetAttr( - kNameSpaceID_None, nsGkAtoms::state, NS_LITERAL_STRING("dragging"), - true); + kNameSpaceID_None, nsGkAtoms::state, u"dragging"_ns, true); } AdjustChildren(aPresContext); } @@ -476,26 +475,18 @@ void nsSplitterFrameInner::MouseDrag(nsPresContext* aPresContext, } void nsSplitterFrameInner::AddListener() { - mOuter->GetContent()->AddEventListener(NS_LITERAL_STRING("mouseup"), this, - false, false); - mOuter->GetContent()->AddEventListener(NS_LITERAL_STRING("mousedown"), this, - false, false); - mOuter->GetContent()->AddEventListener(NS_LITERAL_STRING("mousemove"), this, - false, false); - mOuter->GetContent()->AddEventListener(NS_LITERAL_STRING("mouseout"), this, - false, false); + mOuter->GetContent()->AddEventListener(u"mouseup"_ns, this, false, false); + mOuter->GetContent()->AddEventListener(u"mousedown"_ns, this, false, false); + mOuter->GetContent()->AddEventListener(u"mousemove"_ns, this, false, false); + mOuter->GetContent()->AddEventListener(u"mouseout"_ns, this, false, false); } void nsSplitterFrameInner::RemoveListener() { NS_ENSURE_TRUE_VOID(mOuter); - mOuter->GetContent()->RemoveEventListener(NS_LITERAL_STRING("mouseup"), this, - false); - mOuter->GetContent()->RemoveEventListener(NS_LITERAL_STRING("mousedown"), - this, false); - mOuter->GetContent()->RemoveEventListener(NS_LITERAL_STRING("mousemove"), - this, false); - mOuter->GetContent()->RemoveEventListener(NS_LITERAL_STRING("mouseout"), this, - false); + mOuter->GetContent()->RemoveEventListener(u"mouseup"_ns, this, false); + mOuter->GetContent()->RemoveEventListener(u"mousedown"_ns, this, false); + mOuter->GetContent()->RemoveEventListener(u"mousemove"_ns, this, false); + mOuter->GetContent()->RemoveEventListener(u"mouseout"_ns, this, false); } nsresult nsSplitterFrameInner::HandleEvent(dom::Event* aEvent) { @@ -691,7 +682,7 @@ nsresult nsSplitterFrameInner::MouseMove(Event* aMouseEvent) { nsCOMPtr kungfuDeathGrip(this); mOuter->mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::state, - NS_LITERAL_STRING("dragging"), true); + u"dragging"_ns, true); RemoveListener(); mDragging = true; @@ -771,9 +762,8 @@ void nsSplitterFrameInner::UpdateState() { newState == CollapsedAfter)) { // Open -> CollapsedBefore / CollapsedAfter // Dragging -> CollapsedBefore / CollapsedAfter - nsContentUtils::AddScriptRunner( - new nsSetAttrRunnable(sibling->AsElement(), nsGkAtoms::collapsed, - NS_LITERAL_STRING("true"))); + nsContentUtils::AddScriptRunner(new nsSetAttrRunnable( + sibling->AsElement(), nsGkAtoms::collapsed, u"true"_ns)); } } } diff --git a/layout/xul/nsSplitterFrame.h b/layout/xul/nsSplitterFrame.h index 423d0f9f66da..464e62e3a162 100644 --- a/layout/xul/nsSplitterFrame.h +++ b/layout/xul/nsSplitterFrame.h @@ -33,7 +33,7 @@ class nsSplitterFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("SplitterFrame"), aResult); + return MakeFrameName(u"SplitterFrame"_ns, aResult); } #endif diff --git a/layout/xul/nsStackFrame.h b/layout/xul/nsStackFrame.h index 4403c1bcd8ce..12ecb955eed9 100644 --- a/layout/xul/nsStackFrame.h +++ b/layout/xul/nsStackFrame.h @@ -31,7 +31,7 @@ class nsStackFrame final : public nsBoxFrame { #ifdef DEBUG_FRAME_DUMP virtual nsresult GetFrameName(nsAString& aResult) const override { - return MakeFrameName(NS_LITERAL_STRING("Stack"), aResult); + return MakeFrameName(u"Stack"_ns, aResult); } #endif diff --git a/layout/xul/nsTextBoxFrame.cpp b/layout/xul/nsTextBoxFrame.cpp index f49fe409486a..3b8d25993110 100644 --- a/layout/xul/nsTextBoxFrame.cpp +++ b/layout/xul/nsTextBoxFrame.cpp @@ -768,7 +768,7 @@ nscoord nsTextBoxFrame::CalculateTitleForWidth(gfxContext& aRenderingContext, aRenderingContext); } -#define OLD_ELLIPSIS NS_LITERAL_STRING("...") +#define OLD_ELLIPSIS u"..."_ns // the following block is to append the accesskey to mTitle if there is an // accesskey but the mTitle doesn't have the character @@ -1102,8 +1102,8 @@ nscoord nsTextBoxFrame::GetXULBoxAscent(nsBoxLayoutState& aBoxLayoutState) { #ifdef DEBUG_FRAME_DUMP nsresult nsTextBoxFrame::GetFrameName(nsAString& aResult) const { - MakeFrameName(NS_LITERAL_STRING("TextBox"), aResult); - aResult += NS_LITERAL_STRING("[value=") + mTitle + NS_LITERAL_STRING("]"); + MakeFrameName(u"TextBox"_ns, aResult); + aResult += u"[value="_ns + mTitle + u"]"_ns; return NS_OK; } #endif diff --git a/layout/xul/nsXULLabelFrame.cpp b/layout/xul/nsXULLabelFrame.cpp index 2070eb8d54a0..b2f187dcd4b8 100644 --- a/layout/xul/nsXULLabelFrame.cpp +++ b/layout/xul/nsXULLabelFrame.cpp @@ -91,6 +91,6 @@ nsresult nsXULLabelFrame::AttributeChanged(int32_t aNameSpaceID, #ifdef DEBUG_FRAME_DUMP nsresult nsXULLabelFrame::GetFrameName(nsAString& aResult) const { - return MakeFrameName(NS_LITERAL_STRING("XULLabel"), aResult); + return MakeFrameName(u"XULLabel"_ns, aResult); } #endif diff --git a/layout/xul/nsXULPopupManager.cpp b/layout/xul/nsXULPopupManager.cpp index 6dc9c7e01710..9fc8afa5f63f 100644 --- a/layout/xul/nsXULPopupManager.cpp +++ b/layout/xul/nsXULPopupManager.cpp @@ -159,11 +159,9 @@ nsXULPopupManager::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) { if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) { if (mKeyListener) { - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, - true); - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, - true); - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true); + mKeyListener->RemoveEventListener(u"keypress"_ns, this, true); + mKeyListener->RemoveEventListener(u"keydown"_ns, this, true); + mKeyListener->RemoveEventListener(u"keyup"_ns, this, true); mKeyListener = nullptr; } mRangeParentContent = nullptr; @@ -350,7 +348,7 @@ bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent() { nsAutoString value; element->GetAttr(kNameSpaceID_None, nsGkAtoms::type, value); - return StringBeginsWith(value, NS_LITERAL_STRING("autocomplete")); + return StringBeginsWith(value, u"autocomplete"_ns); } bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent() { @@ -986,8 +984,7 @@ class TransitionEnder final : public nsIDOMEventListener { : mContent(aContent), mDeselectMenu(aDeselectMenu) {} NS_IMETHOD HandleEvent(Event* aEvent) override { - mContent->RemoveSystemEventListener(NS_LITERAL_STRING("transitionend"), - this, false); + mContent->RemoveSystemEventListener(u"transitionend"_ns, this, false); nsMenuPopupFrame* popupFrame = do_QueryFrame(mContent->GetPrimaryFrame()); @@ -1458,8 +1455,8 @@ void nsXULPopupManager::FirePopupHidingEvent( aPopup->AsElement(), PseudoStyleType::NotPseudo)) { RefPtr ender = new TransitionEnder(aPopup, aDeselectMenu); - aPopup->AddSystemEventListener(NS_LITERAL_STRING("transitionend"), - ender, false, false); + aPopup->AddSystemEventListener(u"transitionend"_ns, ender, false, + false); return; } } @@ -1777,19 +1774,17 @@ void nsXULPopupManager::UpdateKeyboardListeners() { if (mKeyListener != newTarget) { if (mKeyListener) { - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, - true); - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, - true); - mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true); + mKeyListener->RemoveEventListener(u"keypress"_ns, this, true); + mKeyListener->RemoveEventListener(u"keydown"_ns, this, true); + mKeyListener->RemoveEventListener(u"keyup"_ns, this, true); mKeyListener = nullptr; nsContentUtils::NotifyInstalledMenuKeyboardListener(false); } if (newTarget) { - newTarget->AddEventListener(NS_LITERAL_STRING("keypress"), this, true); - newTarget->AddEventListener(NS_LITERAL_STRING("keydown"), this, true); - newTarget->AddEventListener(NS_LITERAL_STRING("keyup"), this, true); + newTarget->AddEventListener(u"keypress"_ns, this, true); + newTarget->AddEventListener(u"keydown"_ns, this, true); + newTarget->AddEventListener(u"keyup"_ns, this, true); nsContentUtils::NotifyInstalledMenuKeyboardListener(isForMenu); mKeyListener = newTarget; } @@ -2675,8 +2670,7 @@ nsXULMenuCommandEvent::Run() { if (menuFrame->IsChecked()) { mMenu->UnsetAttr(kNameSpaceID_None, nsGkAtoms::checked, true); } else { - mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, - NS_LITERAL_STRING("true"), true); + mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, u"true"_ns, true); } } diff --git a/layout/xul/nsXULTooltipListener.cpp b/layout/xul/nsXULTooltipListener.cpp index 5d810aad35a3..67dd107e6755 100644 --- a/layout/xul/nsXULTooltipListener.cpp +++ b/layout/xul/nsXULTooltipListener.cpp @@ -292,16 +292,11 @@ void nsXULTooltipListener::AddTooltipSupport(nsIContent* aNode) { MOZ_ASSERT(aNode); MOZ_ASSERT(this == sInstance); - aNode->AddSystemEventListener(NS_LITERAL_STRING("mouseout"), this, false, - false); - aNode->AddSystemEventListener(NS_LITERAL_STRING("mousemove"), this, false, - false); - aNode->AddSystemEventListener(NS_LITERAL_STRING("mousedown"), this, false, - false); - aNode->AddSystemEventListener(NS_LITERAL_STRING("mouseup"), this, false, - false); - aNode->AddSystemEventListener(NS_LITERAL_STRING("dragstart"), this, true, - false); + aNode->AddSystemEventListener(u"mouseout"_ns, this, false, false); + aNode->AddSystemEventListener(u"mousemove"_ns, this, false, false); + aNode->AddSystemEventListener(u"mousedown"_ns, this, false, false); + aNode->AddSystemEventListener(u"mouseup"_ns, this, false, false); + aNode->AddSystemEventListener(u"dragstart"_ns, this, true, false); } void nsXULTooltipListener::RemoveTooltipSupport(nsIContent* aNode) { @@ -311,11 +306,11 @@ void nsXULTooltipListener::RemoveTooltipSupport(nsIContent* aNode) { // The last reference to us can go after some of these calls. RefPtr instance = this; - aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mouseout"), this, false); - aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mousemove"), this, false); - aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"), this, false); - aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mouseup"), this, false); - aNode->RemoveSystemEventListener(NS_LITERAL_STRING("dragstart"), this, true); + aNode->RemoveSystemEventListener(u"mouseout"_ns, this, false); + aNode->RemoveSystemEventListener(u"mousemove"_ns, this, false); + aNode->RemoveSystemEventListener(u"mousedown"_ns, this, false); + aNode->RemoveSystemEventListener(u"mouseup"_ns, this, false); + aNode->RemoveSystemEventListener(u"dragstart"_ns, this, true); } #ifdef MOZ_XUL @@ -393,8 +388,8 @@ nsresult nsXULTooltipListener::ShowTooltip() { // listen for popuphidden on the tooltip node, so that we can // be sure DestroyPopup is called even if someone else closes the tooltip - currentTooltip->AddSystemEventListener(NS_LITERAL_STRING("popuphiding"), - this, false, false); + currentTooltip->AddSystemEventListener(u"popuphiding"_ns, this, false, + false); // listen for mousedown, mouseup, keydown, and DOMMouseScroll events at // document level @@ -405,13 +400,12 @@ nsresult nsXULTooltipListener::ShowTooltip() { // applications. If we don't specify the aWantsUntrusted of // AddSystemEventListener(), the event target sets it to TRUE if the // target is in content. - doc->AddSystemEventListener(NS_LITERAL_STRING("DOMMouseScroll"), this, - true); - doc->AddSystemEventListener(NS_LITERAL_STRING("mousedown"), this, true); - doc->AddSystemEventListener(NS_LITERAL_STRING("mouseup"), this, true); + doc->AddSystemEventListener(u"DOMMouseScroll"_ns, this, true); + doc->AddSystemEventListener(u"mousedown"_ns, this, true); + doc->AddSystemEventListener(u"mouseup"_ns, this, true); #ifndef XP_WIN // On Windows, key events don't close tooltips. - doc->AddSystemEventListener(NS_LITERAL_STRING("keydown"), this, true); + doc->AddSystemEventListener(u"keydown"_ns, this, true); #endif } mSourceNode = nullptr; @@ -450,8 +444,8 @@ void nsXULTooltipListener::LaunchTooltip() { // Because of mutation events, currentTooltip can be null. return; } - currentTooltip->SetAttr(kNameSpaceID_None, nsGkAtoms::titletip, - NS_LITERAL_STRING("true"), true); + currentTooltip->SetAttr(kNameSpaceID_None, nsGkAtoms::titletip, u"true"_ns, + true); } else { currentTooltip->UnsetAttr(kNameSpaceID_None, nsGkAtoms::titletip, true); } @@ -625,19 +619,16 @@ nsresult nsXULTooltipListener::DestroyTooltip() { nsCOMPtr doc = currentTooltip->GetComposedDoc(); if (doc) { // remove the mousedown and keydown listener from document - doc->RemoveSystemEventListener(NS_LITERAL_STRING("DOMMouseScroll"), this, - true); - doc->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"), this, - true); - doc->RemoveSystemEventListener(NS_LITERAL_STRING("mouseup"), this, true); + doc->RemoveSystemEventListener(u"DOMMouseScroll"_ns, this, true); + doc->RemoveSystemEventListener(u"mousedown"_ns, this, true); + doc->RemoveSystemEventListener(u"mouseup"_ns, this, true); #ifndef XP_WIN - doc->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), this, true); + doc->RemoveSystemEventListener(u"keydown"_ns, this, true); #endif } // remove the popuphidden listener from tooltip - currentTooltip->RemoveSystemEventListener(NS_LITERAL_STRING("popuphiding"), - this, false); + currentTooltip->RemoveSystemEventListener(u"popuphiding"_ns, this, false); } // kill any ongoing timers diff --git a/layout/xul/tree/nsTreeBodyFrame.cpp b/layout/xul/tree/nsTreeBodyFrame.cpp index b660819bfc8a..66124e9bb1cf 100644 --- a/layout/xul/tree/nsTreeBodyFrame.cpp +++ b/layout/xul/tree/nsTreeBodyFrame.cpp @@ -404,7 +404,7 @@ nsresult nsTreeBodyFrame::SetView(nsITreeView* aView) { mView); } #endif // #ifdef ACCESSIBILITY - FireDOMEvent(NS_LITERAL_STRING("TreeViewChanged"), treeContent); + FireDOMEvent(u"TreeViewChanged"_ns, treeContent); } if (mView) { @@ -1006,7 +1006,7 @@ nsresult nsTreeBodyFrame::GetCoordsForCellItem(int32_t aRow, nsTreeColumn* aCol, GetTwistyRect(aRow, currCol, imageRect, twistyRect, presContext, twistyContext); - if (NS_LITERAL_CSTRING("twisty").Equals(aElement)) { + if ("twisty"_ns.Equals(aElement)) { // If we're looking for the twisty Rect, just return the size theRect = twistyRect; break; @@ -1028,7 +1028,7 @@ nsresult nsTreeBodyFrame::GetCoordsForCellItem(int32_t aRow, nsTreeColumn* aCol, GetPseudoComputedStyle(nsCSSAnonBoxes::mozTreeImage()); nsRect imageSize = GetImageSize(aRow, currCol, false, imageContext); - if (NS_LITERAL_CSTRING("image").Equals(aElement)) { + if ("image"_ns.Equals(aElement)) { theRect = imageSize; theRect.x = cellX; theRect.y = cellRect.y; @@ -4235,8 +4235,8 @@ void nsTreeBodyFrame::FireRowCountChangedEvent(int32_t aIndex, int32_t aCount) { RefPtr doc = tree->OwnerDoc(); MOZ_ASSERT(doc); - RefPtr event = doc->CreateEvent(NS_LITERAL_STRING("customevent"), - CallerType::System, IgnoreErrors()); + RefPtr event = + doc->CreateEvent(u"customevent"_ns, CallerType::System, IgnoreErrors()); CustomEvent* treeEvent = event->AsCustomEvent(); if (!treeEvent) { @@ -4250,12 +4250,12 @@ void nsTreeBodyFrame::FireRowCountChangedEvent(int32_t aIndex, int32_t aCount) { } // Set 'index' data - the row index rows are changed from. - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("index"), aIndex); + propBag->SetPropertyAsInt32(u"index"_ns, aIndex); // Set 'count' data - the number of changed rows. - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("count"), aCount); + propBag->SetPropertyAsInt32(u"count"_ns, aCount); - InitCustomEvent(treeEvent, NS_LITERAL_STRING("TreeRowCountChanged"), propBag); + InitCustomEvent(treeEvent, u"TreeRowCountChanged"_ns, propBag); event->SetTrusted(true); @@ -4273,8 +4273,8 @@ void nsTreeBodyFrame::FireInvalidateEvent(int32_t aStartRowIdx, RefPtr doc = tree->OwnerDoc(); - RefPtr event = doc->CreateEvent(NS_LITERAL_STRING("customevent"), - CallerType::System, IgnoreErrors()); + RefPtr event = + doc->CreateEvent(u"customevent"_ns, CallerType::System, IgnoreErrors()); CustomEvent* treeEvent = event->AsCustomEvent(); if (!treeEvent) { @@ -4289,24 +4289,24 @@ void nsTreeBodyFrame::FireInvalidateEvent(int32_t aStartRowIdx, if (aStartRowIdx != -1 && aEndRowIdx != -1) { // Set 'startrow' data - the start index of invalidated rows. - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("startrow"), aStartRowIdx); + propBag->SetPropertyAsInt32(u"startrow"_ns, aStartRowIdx); // Set 'endrow' data - the end index of invalidated rows. - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("endrow"), aEndRowIdx); + propBag->SetPropertyAsInt32(u"endrow"_ns, aEndRowIdx); } if (aStartCol && aEndCol) { // Set 'startcolumn' data - the start index of invalidated rows. int32_t startColIdx = aStartCol->GetIndex(); - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("startcolumn"), startColIdx); + propBag->SetPropertyAsInt32(u"startcolumn"_ns, startColIdx); // Set 'endcolumn' data - the start index of invalidated rows. int32_t endColIdx = aEndCol->GetIndex(); - propBag->SetPropertyAsInt32(NS_LITERAL_STRING("endcolumn"), endColIdx); + propBag->SetPropertyAsInt32(u"endcolumn"_ns, endColIdx); } - InitCustomEvent(treeEvent, NS_LITERAL_STRING("TreeInvalidated"), propBag); + InitCustomEvent(treeEvent, u"TreeInvalidated"_ns, propBag); event->SetTrusted(true); diff --git a/layout/xul/tree/nsTreeContentView.cpp b/layout/xul/tree/nsTreeContentView.cpp index 10920dc6a69a..777fa884c820 100644 --- a/layout/xul/tree/nsTreeContentView.cpp +++ b/layout/xul/tree/nsTreeContentView.cpp @@ -541,11 +541,11 @@ void nsTreeContentView::ToggleOpenState(int32_t aRow, ErrorResult& aError) { Row* row = mRows[aRow].get(); if (row->IsOpen()) - row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, - NS_LITERAL_STRING("false"), true); + row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"false"_ns, + true); else - row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, - NS_LITERAL_STRING("true"), true); + row->mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"true"_ns, + true); } NS_IMETHODIMP diff --git a/layout/xul/tree/nsTreeSelection.cpp b/layout/xul/tree/nsTreeSelection.cpp index a91ce5437317..65569847b5dd 100644 --- a/layout/xul/tree/nsTreeSelection.cpp +++ b/layout/xul/tree/nsTreeSelection.cpp @@ -270,7 +270,7 @@ NS_IMETHODIMP nsTreeSelection::GetSingle(bool* aSingle) { } *aSingle = mTree->AttrValueIs(kNameSpaceID_None, nsGkAtoms::seltype, - NS_LITERAL_STRING("single"), eCaseMatters); + u"single"_ns, eCaseMatters); return NS_OK; } @@ -694,9 +694,8 @@ nsTreeSelection::GetShiftSelectPivot(int32_t* aIndex) { nsresult nsTreeSelection::FireOnSelectHandler() { if (mSuppressed || !mTree) return NS_OK; - RefPtr asyncDispatcher = - new AsyncEventDispatcher(mTree, NS_LITERAL_STRING("select"), - CanBubble::eYes, ChromeOnlyDispatch::eNo); + RefPtr asyncDispatcher = new AsyncEventDispatcher( + mTree, u"select"_ns, CanBubble::eYes, ChromeOnlyDispatch::eNo); asyncDispatcher->RunDOMEventWhenSafe(); return NS_OK; } diff --git a/layout/xul/tree/nsTreeUtils.cpp b/layout/xul/tree/nsTreeUtils.cpp index 1ef5cfcb55a5..10767e22d2d9 100644 --- a/layout/xul/tree/nsTreeUtils.cpp +++ b/layout/xul/tree/nsTreeUtils.cpp @@ -89,8 +89,7 @@ nsresult nsTreeUtils::UpdateSortIndicators(dom::Element* aColumn, const nsAString& aDirection) { aColumn->SetAttr(kNameSpaceID_None, nsGkAtoms::sortDirection, aDirection, true); - aColumn->SetAttr(kNameSpaceID_None, nsGkAtoms::sortActive, - NS_LITERAL_STRING("true"), true); + aColumn->SetAttr(kNameSpaceID_None, nsGkAtoms::sortActive, u"true"_ns, true); // Unset sort attribute(s) on the other columns nsCOMPtr parentContent = aColumn->GetParent(); diff --git a/media/mtransport/ipc/WebrtcTCPSocket.cpp b/media/mtransport/ipc/WebrtcTCPSocket.cpp index f6345bd84768..717f26a2b2cd 100644 --- a/media/mtransport/ipc/WebrtcTCPSocket.cpp +++ b/media/mtransport/ipc/WebrtcTCPSocket.cpp @@ -160,8 +160,7 @@ nsresult WebrtcTCPSocket::Open( } mOpened = true; - nsCString schemePrefix = - aUseTls ? NS_LITERAL_CSTRING("https://") : NS_LITERAL_CSTRING("http://"); + nsCString schemePrefix = aUseTls ? "https://"_ns : "http://"_ns; nsCString spec = schemePrefix + aHost; nsresult rv = NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID) @@ -296,7 +295,7 @@ void WebrtcTCPSocket::OpenWithoutHttpProxy(nsIProxyInfo* aSocksProxyInfo) { AutoTArray socketTypes; if (mTls) { - socketTypes.AppendElement(NS_LITERAL_CSTRING("ssl")); + socketTypes.AppendElement("ssl"_ns); } nsCOMPtr sts = diff --git a/media/mtransport/nr_socket_prsock.cpp b/media/mtransport/nr_socket_prsock.cpp index 057abda707ad..5cc4292cedf2 100644 --- a/media/mtransport/nr_socket_prsock.cpp +++ b/media/mtransport/nr_socket_prsock.cpp @@ -250,7 +250,7 @@ static nsIThread* GetIOThreadAndAddUse_s() { #if defined(MOZILLA_INTERNAL_API) // We need to safely release this on shutdown to avoid leaks if (!sThread) { - sThread = new SingletonThreadHolder(NS_LITERAL_CSTRING("mtransport")); + sThread = new SingletonThreadHolder("mtransport"_ns); NS_DispatchToMainThread(mozilla::WrapRunnableNM(&ClearSingletonOnShutdown)); } // Mark that we're using the shared thread and need it to stick around diff --git a/media/mtransport/test/proxy_tunnel_socket_unittest.cpp b/media/mtransport/test/proxy_tunnel_socket_unittest.cpp index 75dbe661dabf..ea4ccbcb7e47 100644 --- a/media/mtransport/test/proxy_tunnel_socket_unittest.cpp +++ b/media/mtransport/test/proxy_tunnel_socket_unittest.cpp @@ -104,7 +104,7 @@ TEST_F(NrTcpSocketTest, TestConnected) { // still not connected just registered for writes... ASSERT_TRUE(!mConnected); - mSProxy->OnConnected(NS_LITERAL_CSTRING("http")); + mSProxy->OnConnected("http"_ns); ASSERT_TRUE(mConnected); } diff --git a/media/mtransport/test/webrtcproxychannel_unittest.cpp b/media/mtransport/test/webrtcproxychannel_unittest.cpp index e957ae8bcb23..02fe7c74d23e 100644 --- a/media/mtransport/test/webrtcproxychannel_unittest.cpp +++ b/media/mtransport/test/webrtcproxychannel_unittest.cpp @@ -472,7 +472,7 @@ void FakeWebrtcTCPSocket::InvokeOnClose(nsresult aReason) { } void FakeWebrtcTCPSocket::InvokeOnConnected() { - mProxyCallbacks->OnConnected(NS_LITERAL_CSTRING("http")); + mProxyCallbacks->OnConnected("http"_ns); } void FakeWebrtcTCPSocket::InvokeOnRead(nsTArray&& aReadData) { diff --git a/media/webrtc/signaling/src/media-conduit/WebrtcGmpVideoCodec.cpp b/media/webrtc/signaling/src/media-conduit/WebrtcGmpVideoCodec.cpp index ce9af67684a3..4b502c3f2b88 100644 --- a/media/webrtc/signaling/src/media-conduit/WebrtcGmpVideoCodec.cpp +++ b/media/webrtc/signaling/src/media-conduit/WebrtcGmpVideoCodec.cpp @@ -193,12 +193,12 @@ void WebrtcGmpVideoEncoder::InitEncode_g( const GMPVideoCodec& aCodecParams, int32_t aNumberOfCores, uint32_t aMaxPayloadSize, const RefPtr& aInitDone) { nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); + tags.AppendElement("h264"_ns); UniquePtr callback( new InitDoneCallback(aThis, aInitDone, aCodecParams, aMaxPayloadSize)); aThis->mInitting = true; - nsresult rv = aThis->mMPS->GetGMPVideoEncoder( - nullptr, &tags, NS_LITERAL_CSTRING(""), std::move(callback)); + nsresult rv = aThis->mMPS->GetGMPVideoEncoder(nullptr, &tags, ""_ns, + std::move(callback)); if (NS_WARN_IF(NS_FAILED(rv))) { GMP_LOG_DEBUG("GMP Encode: GetGMPVideoEncoder failed"); aThis->Close_g(); @@ -312,10 +312,10 @@ void WebrtcGmpVideoEncoder::RegetEncoderForResolutionChange( // re-init the plugin when the resolution changes // XXX allow codec to indicate it doesn't need re-init! nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); + tags.AppendElement("h264"_ns); mInitting = true; - if (NS_WARN_IF(NS_FAILED(mMPS->GetGMPVideoEncoder( - nullptr, &tags, NS_LITERAL_CSTRING(""), std::move(callback))))) { + if (NS_WARN_IF(NS_FAILED(mMPS->GetGMPVideoEncoder(nullptr, &tags, ""_ns, + std::move(callback))))) { aInitDone->Dispatch(WEBRTC_VIDEO_CODEC_ERROR, "GMP Encode: GetGMPVideoEncoder failed"); } @@ -684,12 +684,12 @@ void WebrtcGmpVideoDecoder::InitDecode_g( const webrtc::VideoCodec* aCodecSettings, int32_t aNumberOfCores, const RefPtr& aInitDone) { nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); + tags.AppendElement("h264"_ns); UniquePtr callback( new InitDoneCallback(aThis, aInitDone)); aThis->mInitting = true; - nsresult rv = aThis->mMPS->GetGMPVideoDecoder( - nullptr, &tags, NS_LITERAL_CSTRING(""), std::move(callback)); + nsresult rv = aThis->mMPS->GetGMPVideoDecoder(nullptr, &tags, ""_ns, + std::move(callback)); if (NS_WARN_IF(NS_FAILED(rv))) { GMP_LOG_DEBUG("GMP Decode: GetGMPVideoDecoder failed"); aThis->Close_g(); diff --git a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp index ceb409e1951f..03a631461afc 100644 --- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp +++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp @@ -1797,7 +1797,7 @@ MediaPipeline::RtpCSRCStats::RtpCSRCStats(const uint32_t aCsrc, void MediaPipeline::RtpCSRCStats::GetWebidlInstance( dom::RTCRTPContributingSourceStats& aWebidlObj, const nsString& aInboundRtpStreamId) const { - nsString statId = NS_LITERAL_STRING("csrc_") + aInboundRtpStreamId; + nsString statId = u"csrc_"_ns + aInboundRtpStreamId; statId.AppendLiteral("_"); statId.AppendInt(mCsrc); aWebidlObj.mId.Construct(statId); diff --git a/media/webrtc/signaling/src/peerconnection/MediaTransportHandler.cpp b/media/webrtc/signaling/src/peerconnection/MediaTransportHandler.cpp index cf67fb743c61..29d8e5449e6b 100644 --- a/media/webrtc/signaling/src/peerconnection/MediaTransportHandler.cpp +++ b/media/webrtc/signaling/src/peerconnection/MediaTransportHandler.cpp @@ -257,7 +257,7 @@ static nsresult addNrIceServer(const nsString& aIceUrl, // Tolerate query-string + parse 'transport=[udp|tcp]' by hand. int32_t questionmark = path.FindChar('?'); if (questionmark >= 0) { - const nsCString match = NS_LITERAL_CSTRING("transport="); + const nsCString match = "transport="_ns; for (int32_t i = questionmark, endPos; i >= 0; i = endPos) { endPos = path.FindCharInSet("&", i + 1); diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp index e0e2fad58d7c..5ff2f4f581c3 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionCtx.cpp @@ -386,17 +386,17 @@ bool PeerConnectionCtx::gmpHasH264() { // XXX I'd prefer if this was all known ahead of time... nsTArray tags; - tags.AppendElement(NS_LITERAL_CSTRING("h264")); + tags.AppendElement("h264"_ns); bool has_gmp; nsresult rv; - rv = mGMPService->HasPluginForAPI(NS_LITERAL_CSTRING(GMP_API_VIDEO_ENCODER), + rv = mGMPService->HasPluginForAPI(nsLiteralCString(GMP_API_VIDEO_ENCODER), &tags, &has_gmp); if (NS_FAILED(rv) || !has_gmp) { return false; } - rv = mGMPService->HasPluginForAPI(NS_LITERAL_CSTRING(GMP_API_VIDEO_DECODER), + rv = mGMPService->HasPluginForAPI(nsLiteralCString(GMP_API_VIDEO_DECODER), &tags, &has_gmp); if (NS_FAILED(rv) || !has_gmp) { return false; diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp index 69c0d21588d0..cf7a0c3776e2 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp @@ -2044,8 +2044,8 @@ bool PeerConnectionImpl::PluginCrash(uint32_t aPluginID, init.mBubbles = true; init.mCancelable = true; - RefPtr event = PluginCrashedEvent::Constructor( - doc, NS_LITERAL_STRING("PluginCrashed"), init); + RefPtr event = + PluginCrashedEvent::Constructor(doc, u"PluginCrashed"_ns, init); event->SetTrusted(true); event->WidgetEventPtr()->mFlags.mOnlyChromeDispatch = true; @@ -2569,15 +2569,14 @@ static UniquePtr GetSenderStats_s( UniquePtr report(new dom::RTCStatsCollection); auto asVideo = aPipeline->Conduit()->AsVideoSessionConduit(); - nsString kind = asVideo.isNothing() ? NS_LITERAL_STRING("audio") - : NS_LITERAL_STRING("video"); - nsString idstr = kind + NS_LITERAL_STRING("_"); + nsString kind = asVideo.isNothing() ? u"audio"_ns : u"video"_ns; + nsString idstr = kind + u"_"_ns; idstr.AppendInt(static_cast(aPipeline->Level())); // TODO(@@NG):ssrcs handle Conduits having multiple stats at the same level // This is pending spec work // Gather pipeline stats. - nsString localId = NS_LITERAL_STRING("outbound_rtp_") + idstr; + nsString localId = u"outbound_rtp_"_ns + idstr; nsString remoteId; Maybe ssrc; std::vector ssrcvals = aPipeline->Conduit()->GetLocalSSRCs(); @@ -2598,7 +2597,7 @@ static UniquePtr GetSenderStats_s( if (timestamp.isSome() && aPipeline->Conduit()->GetRTCPReceiverReport( &jitterMs, &packetsReceived, &bytesReceived, &packetsLost, &rtt)) { - remoteId = NS_LITERAL_STRING("outbound_rtcp_") + idstr; + remoteId = u"outbound_rtcp_"_ns + idstr; RTCRemoteInboundRtpStreamStats s; s.mTimestamp.Construct(*timestamp); s.mId.Construct(remoteId); diff --git a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp index 8e88be43515d..7effe405f3b8 100644 --- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp +++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp @@ -824,7 +824,7 @@ std::unique_ptr PeerConnectionMedia::GetProxyConfig() return nullptr; } - nsCString alpn = NS_LITERAL_CSTRING("webrtc,c-webrtc"); + nsCString alpn = "webrtc,c-webrtc"_ns; auto browserChild = BrowserChild::GetFrom(GetWindow()); if (!browserChild) { // Android doesn't have browser child apparently... diff --git a/media/webrtc/signaling/src/peerconnection/RTCDTMFSender.cpp b/media/webrtc/signaling/src/peerconnection/RTCDTMFSender.cpp index fbf6a37b8dc3..8b5c3c9da176 100644 --- a/media/webrtc/signaling/src/peerconnection/RTCDTMFSender.cpp +++ b/media/webrtc/signaling/src/peerconnection/RTCDTMFSender.cpp @@ -134,8 +134,8 @@ nsresult RTCDTMFSender::Notify(nsITimer* timer) { } } - RefPtr event = RTCDTMFToneChangeEvent::Constructor( - this, NS_LITERAL_STRING("tonechange"), init); + RefPtr event = + RTCDTMFToneChangeEvent::Constructor(this, u"tonechange"_ns, init); DispatchTrustedEvent(event); return NS_OK; diff --git a/media/webrtc/signaling/src/peerconnection/RTCRtpReceiver.cpp b/media/webrtc/signaling/src/peerconnection/RTCRtpReceiver.cpp index 4489ea4b77c0..1c7404d5a3e9 100644 --- a/media/webrtc/signaling/src/peerconnection/RTCRtpReceiver.cpp +++ b/media/webrtc/signaling/src/peerconnection/RTCRtpReceiver.cpp @@ -70,14 +70,12 @@ static already_AddRefed CreateTrack( if (aAudio) { RefPtr source = graph->CreateSourceTrack(MediaSegment::AUDIO); - trackSource = new RemoteTrackSource(source, aPrincipal, - NS_LITERAL_STRING("remote audio")); + trackSource = new RemoteTrackSource(source, aPrincipal, u"remote audio"_ns); track = new AudioStreamTrack(aWindow, source, trackSource); } else { RefPtr source = graph->CreateSourceTrack(MediaSegment::VIDEO); - trackSource = new RemoteTrackSource(source, aPrincipal, - NS_LITERAL_STRING("remote video")); + trackSource = new RemoteTrackSource(source, aPrincipal, u"remote video"_ns); track = new VideoStreamTrack(aWindow, source, trackSource); } @@ -162,9 +160,8 @@ static UniquePtr GetReceiverStats_s( UniquePtr report(new dom::RTCStatsCollection); auto asVideo = aPipeline->Conduit()->AsVideoSessionConduit(); - nsString kind = asVideo.isNothing() ? NS_LITERAL_STRING("audio") - : NS_LITERAL_STRING("video"); - nsString idstr = kind + NS_LITERAL_STRING("_"); + nsString kind = asVideo.isNothing() ? u"audio"_ns : u"video"_ns; + nsString idstr = kind + u"_"_ns; idstr.AppendInt(static_cast(aPipeline->Level())); Maybe ssrc; @@ -184,7 +181,7 @@ static UniquePtr GetReceiverStats_s( // TODO(@@NG):ssrcs handle Conduits having multiple stats at the same level // This is pending spec work // Gather pipeline stats. - nsString localId = NS_LITERAL_STRING("inbound_rtp_") + idstr; + nsString localId = u"inbound_rtp_"_ns + idstr; nsString remoteId; // First, fill in remote stat with rtcp sender data, if present. @@ -196,7 +193,7 @@ static UniquePtr GetReceiverStats_s( if (timestamp.isSome() && aPipeline->Conduit()->GetRTCPSenderReport( &packetsSent, &bytesSent, &remoteTimestamp)) { RTCRemoteOutboundRtpStreamStats s; - remoteId = NS_LITERAL_STRING("inbound_rtcp_") + idstr; + remoteId = u"inbound_rtcp_"_ns + idstr; s.mTimestamp.Construct(*timestamp); s.mId.Construct(remoteId); s.mType.Construct(RTCStatsType::Remote_outbound_rtp); diff --git a/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h b/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h index e42493470abe..4360f312899e 100644 --- a/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h +++ b/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h @@ -25,8 +25,7 @@ class RemoteTrackSource : public dom::MediaStreamTrackSource { dom::CallerType aCallerType) override { return ApplyConstraintsPromise::CreateAndReject( MakeRefPtr( - dom::MediaStreamError::Name::OverconstrainedError, - NS_LITERAL_STRING("")), + dom::MediaStreamError::Name::OverconstrainedError, u""_ns), __func__); } diff --git a/media/webrtc/signaling/src/peerconnection/WebrtcGlobalInformation.cpp b/media/webrtc/signaling/src/peerconnection/WebrtcGlobalInformation.cpp index a40b8dfcb4b9..f1592023179d 100644 --- a/media/webrtc/signaling/src/peerconnection/WebrtcGlobalInformation.cpp +++ b/media/webrtc/signaling/src/peerconnection/WebrtcGlobalInformation.cpp @@ -282,8 +282,7 @@ static void OnGetLogging_m(WebrtcGlobalChild* aThisChild, const int aRequestId, MOZ_ASSERT(NS_IsMainThread()); if (!aLogList.IsEmpty()) { - if (!aLogList.AppendElement(NS_LITERAL_STRING("+++++++ END ++++++++"), - fallible)) { + if (!aLogList.AppendElement(u"+++++++ END ++++++++"_ns, fallible)) { mozalloc_handle_oom(0); } } diff --git a/media/webrtc/signaling/src/sdp/ParsingResultComparer.cpp b/media/webrtc/signaling/src/sdp/ParsingResultComparer.cpp index dcb03bf320f1..d357ffc8c99e 100644 --- a/media/webrtc/signaling/src/sdp/ParsingResultComparer.cpp +++ b/media/webrtc/signaling/src/sdp/ParsingResultComparer.cpp @@ -79,7 +79,7 @@ bool ParsingResultComparer::Compare(const Sdp& rsdparsaSdp, const Sdp& sipccSdp, LOG_EXPECT(result, expect, ("The original sdp: \n%s", mOriginalSdp.c_str())); if (result) { Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, - NS_LITERAL_STRING("serialization_is_equal"), 1); + u"serialization_is_equal"_ns, 1); LOG_EXPECT(result, expect, ("Serialization is equal")); return result; } @@ -87,7 +87,7 @@ bool ParsingResultComparer::Compare(const Sdp& rsdparsaSdp, const Sdp& sipccSdp, result = true; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, - NS_LITERAL_STRING("serialization_is_not_equal"), 1); + u"serialization_is_not_equal"_ns, 1); LOG_EXPECT(result, expect, ("Serialization is not equal\n" " --- Sipcc SDP ---\n" @@ -101,8 +101,8 @@ bool ParsingResultComparer::Compare(const Sdp& rsdparsaSdp, const Sdp& sipccSdp, // Compare the session level if (rsdparsaOriginStr != sipccOriginStr) { - Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, - NS_LITERAL_STRING("o="), 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, u"o="_ns, + 1); result = false; LOG_EXPECT(result, expect, ("origin is not equal\nrust origin: %s\nsipcc origin: %s", @@ -132,7 +132,7 @@ bool ParsingResultComparer::Compare(const Sdp& rsdparsaSdp, const Sdp& sipccSdp, if (sipccMediaSecCount != rsdparsaMediaSecCount) { result = false; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, - NS_LITERAL_STRING("inequal_msec_count"), 1); + u"inequal_msec_count"_ns, 1); LOG_EXPECT(result, expect, ("Media section count is NOT equal, rsdparsa: %d, sipcc: %d \n", rsdparsaMediaSecCount, sipccMediaSecCount)); @@ -156,7 +156,7 @@ bool ParsingResultComparer::CompareMediaSections( auto rustValue, auto sipccValue, const nsString& valueDescription) { result = false; - nsString typeStr = NS_LITERAL_STRING("m="); + nsString typeStr = u"m="_ns; typeStr += valueDescription; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, typeStr, 1); @@ -184,26 +184,19 @@ bool ParsingResultComparer::CompareMediaSections( valueDescription); }; - compareSimpleMediaLineValue(&SdpMediaSection::GetMediaType, - NS_LITERAL_STRING("media_type")); - compareSimpleMediaLineValue(&SdpMediaSection::GetPort, - NS_LITERAL_STRING("port")); - compareSimpleMediaLineValue(&SdpMediaSection::GetPortCount, - NS_LITERAL_STRING("port_count")); - compareSimpleMediaLineValue(&SdpMediaSection::GetProtocol, - NS_LITERAL_STRING("protocol")); + compareSimpleMediaLineValue(&SdpMediaSection::GetMediaType, u"media_type"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::GetPort, u"port"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::GetPortCount, u"port_count"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::GetProtocol, u"protocol"_ns); compareSimpleMediaLineValue(&SdpMediaSection::IsReceiving, - NS_LITERAL_STRING("is_receiving")); - compareSimpleMediaLineValue(&SdpMediaSection::IsSending, - NS_LITERAL_STRING("is_sending")); - compareSimpleMediaLineValue(&SdpMediaSection::GetDirection, - NS_LITERAL_STRING("direction")); - compareSimpleMediaLineValue(&SdpMediaSection::GetLevel, - NS_LITERAL_STRING("level")); + u"is_receiving"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::IsSending, u"is_sending"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::GetDirection, u"direction"_ns); + compareSimpleMediaLineValue(&SdpMediaSection::GetLevel, u"level"_ns); compareMediaLineValue(ToString(rustMediaSection.GetConnection()), ToString(sipccMediaSection.GetConnection()), - NS_LITERAL_STRING("connection")); + u"connection"_ns); result &= CompareAttrLists(rustMediaSection.GetAttributeList(), sipccMediaSection.GetAttributeList(), @@ -233,7 +226,7 @@ bool ParsingResultComparer::CompareAttrLists( result = false; nsString typeStr; typeStr.AssignASCII(attrStr.c_str()); - typeStr += NS_LITERAL_STRING("_missing"); + typeStr += u"_missing"_ns; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, typeStr, 1); LOG_EXPECT(result, expect, @@ -258,7 +251,7 @@ bool ParsingResultComparer::CompareAttrLists( result = false; nsString typeStr; typeStr.AssignASCII(attrStr.c_str()); - typeStr += NS_LITERAL_STRING("_inequal"); + typeStr += u"_inequal"_ns; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, typeStr, 1); LOG_EXPECT(result, expect, @@ -281,7 +274,7 @@ bool ParsingResultComparer::CompareAttrLists( if (rustAttrlist.HasAttribute(type, false)) { nsString typeStr; typeStr.AssignASCII(attrStr.c_str()); - typeStr += NS_LITERAL_STRING("_unexpected"); + typeStr += u"_unexpected"_ns; Telemetry::ScalarAdd(Telemetry::ScalarID::WEBRTC_SDP_PARSER_DIFF, typeStr, 1); } diff --git a/mobile/android/components/geckoview/GeckoViewExternalAppService.cpp b/mobile/android/components/geckoview/GeckoViewExternalAppService.cpp index 18d21728d61a..0b4abe38bf32 100644 --- a/mobile/android/components/geckoview/GeckoViewExternalAppService.cpp +++ b/mobile/android/components/geckoview/GeckoViewExternalAppService.cpp @@ -87,7 +87,7 @@ NS_IMETHODIMP GeckoViewExternalAppService::CreateListener( return NS_ERROR_ABORT; } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("uri"))); + keys.AppendElement(jni::StringParam(u"uri"_ns)); values.AppendElement(jni::StringParam(uriSpec)); nsCString contentType; @@ -95,7 +95,7 @@ NS_IMETHODIMP GeckoViewExternalAppService::CreateListener( return NS_ERROR_ABORT; } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("contentType"))); + keys.AppendElement(jni::StringParam(u"contentType"_ns)); values.AppendElement(jni::StringParam(contentType)); int64_t contentLength = 0; @@ -103,12 +103,12 @@ NS_IMETHODIMP GeckoViewExternalAppService::CreateListener( return NS_ERROR_ABORT; } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("contentLength"))); + keys.AppendElement(jni::StringParam(u"contentLength"_ns)); values.AppendElement(java::sdk::Long::ValueOf(contentLength)); nsString filename; if (NS_SUCCEEDED(channel->GetContentDispositionFilename(filename))) { - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("filename"))); + keys.AppendElement(jni::StringParam(u"filename"_ns)); values.AppendElement(jni::StringParam(filename)); } diff --git a/mobile/android/components/geckoview/GeckoViewHistory.cpp b/mobile/android/components/geckoview/GeckoViewHistory.cpp index ad107bfe932a..17122a5fe0f6 100644 --- a/mobile/android/components/geckoview/GeckoViewHistory.cpp +++ b/mobile/android/components/geckoview/GeckoViewHistory.cpp @@ -279,7 +279,7 @@ GeckoViewHistory::VisitURI(nsIWidget* aWidget, nsIURI* aURI, if (NS_WARN_IF(NS_FAILED(aURI->GetSpec(uriSpec)))) { return NS_OK; } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("url"))); + keys.AppendElement(jni::StringParam(u"url"_ns)); values.AppendElement(jni::StringParam(uriSpec)); if (aLastVisitedURI) { @@ -287,7 +287,7 @@ GeckoViewHistory::VisitURI(nsIWidget* aWidget, nsIURI* aURI, if (NS_WARN_IF(NS_FAILED(aLastVisitedURI->GetSpec(lastVisitedURISpec)))) { return NS_OK; } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("lastVisitedURL"))); + keys.AppendElement(jni::StringParam(u"lastVisitedURL"_ns)); values.AppendElement(jni::StringParam(lastVisitedURISpec)); } @@ -314,7 +314,7 @@ GeckoViewHistory::VisitURI(nsIWidget* aWidget, nsIURI* aURI, flags |= static_cast(GeckoViewVisitFlags::VISIT_UNRECOVERABLE_ERROR); } - keys.AppendElement(jni::StringParam(NS_LITERAL_STRING("flags"))); + keys.AppendElement(jni::StringParam(u"flags"_ns)); values.AppendElement(java::sdk::Integer::ValueOf(flags)); MOZ_ASSERT(keys.Length() == values.Length()); @@ -463,7 +463,7 @@ void GeckoViewHistory::QueryVisitedState( } auto bundleKeys = jni::ObjectArray::New(1); - jni::String::LocalRef key(jni::StringParam(NS_LITERAL_STRING("urls"))); + jni::String::LocalRef key(jni::StringParam(u"urls"_ns)); bundleKeys->SetElement(0, key); auto bundleValues = jni::ObjectArray::New(1); diff --git a/modules/libjar/nsJARInputStream.cpp b/modules/libjar/nsJARInputStream.cpp index 668e116bd01f..7dd4b28720f1 100644 --- a/modules/libjar/nsJARInputStream.cpp +++ b/modules/libjar/nsJARInputStream.cpp @@ -124,8 +124,7 @@ nsresult nsJARInputStream::InitDirectory(nsJAR* aJar, } ++curr; } - nsAutoCString pattern = escDirName + NS_LITERAL_CSTRING("?*~") + escDirName + - NS_LITERAL_CSTRING("?*/?*"); + nsAutoCString pattern = escDirName + "?*~"_ns + escDirName + "?*/?*"_ns; rv = mJar->mZip->FindInit(pattern.get(), &find); if (NS_FAILED(rv)) return rv; diff --git a/modules/libjar/nsJARURI.cpp b/modules/libjar/nsJARURI.cpp index 7e0f547c4245..401abbd62d93 100644 --- a/modules/libjar/nsJARURI.cpp +++ b/modules/libjar/nsJARURI.cpp @@ -47,9 +47,9 @@ nsresult nsJARURI::Init(const char* charsetHint) { return NS_OK; } -#define NS_JAR_SCHEME NS_LITERAL_CSTRING("jar:") -#define NS_JAR_DELIMITER NS_LITERAL_CSTRING("!/") -#define NS_BOGUS_ENTRY_SCHEME NS_LITERAL_CSTRING("x:///") +#define NS_JAR_SCHEME "jar:"_ns +#define NS_JAR_DELIMITER "!/"_ns +#define NS_BOGUS_ENTRY_SCHEME "x:///"_ns // FormatSpec takes the entry spec (including the "x:///" at the // beginning) and gives us a full JAR spec. diff --git a/modules/libjar/zipwriter/nsZipHeader.cpp b/modules/libjar/zipwriter/nsZipHeader.cpp index 2115a9677454..0a42527317b9 100644 --- a/modules/libjar/zipwriter/nsZipHeader.cpp +++ b/modules/libjar/zipwriter/nsZipHeader.cpp @@ -162,7 +162,7 @@ nsresult nsZipHeader::Init(const nsACString& aPath, PRTime aDate, mEAttr = aAttr; mOffset = aOffset; mName = aPath; - mComment = NS_LITERAL_CSTRING(""); + mComment = ""_ns; // Claim a UTF-8 path in case it needs it. mFlags |= FLAGS_IS_UTF8; mInited = true; @@ -282,7 +282,7 @@ nsresult nsZipHeader::ReadCDSHeader(nsIInputStream* stream) { NS_ENSURE_SUCCESS(rv, rv); mName.Assign(field.get(), namelength); } else - mName = NS_LITERAL_CSTRING(""); + mName = ""_ns; if (mFieldLength > 0) { mExtraField = MakeUnique(mFieldLength); @@ -298,7 +298,7 @@ nsresult nsZipHeader::ReadCDSHeader(nsIInputStream* stream) { NS_ENSURE_SUCCESS(rv, rv); mComment.Assign(field.get(), commentlength); } else - mComment = NS_LITERAL_CSTRING(""); + mComment = ""_ns; mInited = true; return NS_OK; diff --git a/modules/libjar/zipwriter/nsZipWriter.cpp b/modules/libjar/zipwriter/nsZipWriter.cpp index e129f64cbd36..b634a042471a 100644 --- a/modules/libjar/zipwriter/nsZipWriter.cpp +++ b/modules/libjar/zipwriter/nsZipWriter.cpp @@ -792,7 +792,7 @@ nsresult nsZipWriter::InternalAddEntryDirectory(const nsACString& aZipEntry, nsresult rv = NS_OK; if (aZipEntry.Last() != '/') { nsCString dirPath; - dirPath.Assign(aZipEntry + NS_LITERAL_CSTRING("/")); + dirPath.Assign(aZipEntry + "/"_ns); rv = header->Init(dirPath, aModTime, zipAttributes, mCDSOffset); } else { rv = header->Init(aZipEntry, aModTime, zipAttributes, mCDSOffset); diff --git a/modules/libpref/Preferences.cpp b/modules/libpref/Preferences.cpp index 9333e53c2652..18777213c9e9 100644 --- a/modules/libpref/Preferences.cpp +++ b/modules/libpref/Preferences.cpp @@ -2605,8 +2605,7 @@ nsPrefBranch::DeleteBranch(const char* aStartingAt) { nsAutoCString branchName(pref.get()); // Add a trailing '.' if it doesn't already have one. - if (branchName.Length() > 1 && - !StringEndsWith(branchName, NS_LITERAL_CSTRING("."))) { + if (branchName.Length() > 1 && !StringEndsWith(branchName, "."_ns)) { branchName += '.'; } @@ -3268,9 +3267,9 @@ PreferenceServiceReporter::CollectReports( aHandleReport->Callback( /* process = */ EmptyCString(), suspectPath, KIND_OTHER, UNITS_COUNT, totalReferentCount, - NS_LITERAL_CSTRING("A preference with a suspiciously large number " - "referents (symptom of a " - "leak)."), + nsLiteralCString("A preference with a suspiciously large number " + "referents (symptom of a " + "leak)."), aData); } @@ -4028,7 +4027,7 @@ void Preferences::ReadUserOverridePrefs() { return; } - aFile->AppendNative(NS_LITERAL_CSTRING("user.js")); + aFile->AppendNative("user.js"_ns); rv = openPrefFile(aFile, PrefValueKind::User); if (rv != NS_ERROR_FILE_NOT_FOUND) { // If the file exists and was at least partially read, record that in @@ -4200,7 +4199,7 @@ static nsresult openPrefFile(nsIFile* aFile, PrefValueKind aKind) { static nsresult parsePrefData(const nsCString& aData, PrefValueKind aKind) { TimeStamp startTime = TimeStamp::Now(); - const nsCString path = NS_LITERAL_CSTRING("$MOZ_DEFAULT_PREFS"); + const nsCString path = "$MOZ_DEFAULT_PREFS"_ns; Parser parser; if (!parser.Parse(path, aKind, path.get(), startTime, aData)) { @@ -4257,7 +4256,7 @@ static nsresult pref_LoadPrefsInDir(nsIFile* aDir, "Failure in default prefs: directory enumerator returned empty file?"); // Skip non-js files. - if (StringEndsWith(leafName, NS_LITERAL_CSTRING(".js"), + if (StringEndsWith(leafName, ".js"_ns, nsCaseInsensitiveCStringComparator)) { bool shouldParse = true; @@ -4549,7 +4548,7 @@ nsresult Preferences::InitInitialObjects(bool aIsStartup) { rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(greprefsFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = greprefsFile->AppendNative(NS_LITERAL_CSTRING("greprefs.js")); + rv = greprefsFile->AppendNative("greprefs.js"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = openPrefFile(greprefsFile, PrefValueKind::Default); @@ -5366,7 +5365,7 @@ static void InitAll() { // which prevents automatic int-to-float coercion. #define NEVER_PREF(name, cpp_type, value) InitPref_##cpp_type(name, value); #define ALWAYS_PREF(name, base_id, full_id, cpp_type, value) \ - InitAlwaysPref(NS_LITERAL_CSTRING(name), &sMirror_##full_id, value); + InitAlwaysPref(nsLiteralCString(name), &sMirror_##full_id, value); #define ONCE_PREF(name, base_id, full_id, cpp_type, value) \ InitPref_##cpp_type(name, value); #include "mozilla/StaticPrefListAll.h" @@ -5384,7 +5383,7 @@ static void StartObservingAlwaysPrefs() { // since the call to InitAll(). #define NEVER_PREF(name, cpp_type, value) #define ALWAYS_PREF(name, base_id, full_id, cpp_type, value) \ - AddMirror(&sMirror_##full_id, NS_LITERAL_CSTRING(name), sMirror_##full_id); + AddMirror(&sMirror_##full_id, nsLiteralCString(name), sMirror_##full_id); #define ONCE_PREF(name, base_id, full_id, cpp_type, value) #include "mozilla/StaticPrefListAll.h" #undef NEVER_PREF diff --git a/modules/libpref/test/gtest/CallbackAndVarCacheOrder.cpp b/modules/libpref/test/gtest/CallbackAndVarCacheOrder.cpp index 1064108d9ba7..ea65f7211cb9 100644 --- a/modules/libpref/test/gtest/CallbackAndVarCacheOrder.cpp +++ b/modules/libpref/test/gtest/CallbackAndVarCacheOrder.cpp @@ -134,69 +134,54 @@ void RunTest(const nsCString& aPrefName1, const nsCString& aPrefName2, } TEST(CallbackAndVarCacheOrder, Bool) -{ - RunTest(NS_LITERAL_CSTRING("test_pref.bool.1"), - NS_LITERAL_CSTRING("test_pref.bool.2"), false, true); -} +{ RunTest("test_pref.bool.1"_ns, "test_pref.bool.2"_ns, false, true); } TEST(CallbackAndVarCacheOrder, AtomicBoolRelaxed) { RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_bool.1"), - NS_LITERAL_CSTRING("test_pref.atomic_bool.2"), false, true); + "test_pref.atomic_bool.1"_ns, "test_pref.atomic_bool.2"_ns, false, true); } TEST(CallbackAndVarCacheOrder, AtomicBoolReleaseAcquire) { RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_bool.3"), - NS_LITERAL_CSTRING("test_pref.atomic_bool.4"), false, true); + "test_pref.atomic_bool.3"_ns, "test_pref.atomic_bool.4"_ns, false, true); } TEST(CallbackAndVarCacheOrder, Int) -{ - RunTest(NS_LITERAL_CSTRING("test_pref.int.1"), - NS_LITERAL_CSTRING("test_pref.int.2"), -2, 3); -} +{ RunTest("test_pref.int.1"_ns, "test_pref.int.2"_ns, -2, 3); } TEST(CallbackAndVarCacheOrder, AtomicInt) { RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_int.1"), - NS_LITERAL_CSTRING("test_pref.atomic_int.2"), -3, 4); + "test_pref.atomic_int.1"_ns, "test_pref.atomic_int.2"_ns, -3, 4); } TEST(CallbackAndVarCacheOrder, Uint) -{ - RunTest(NS_LITERAL_CSTRING("test_pref.uint.1"), - NS_LITERAL_CSTRING("test_pref.uint.2"), 4u, 5u); -} +{ RunTest("test_pref.uint.1"_ns, "test_pref.uint.2"_ns, 4u, 5u); } TEST(CallbackAndVarCacheOrder, AtomicUintRelaxed) { RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_uint.1"), - NS_LITERAL_CSTRING("test_pref.atomic_uint.2"), 6u, 7u); + "test_pref.atomic_uint.1"_ns, "test_pref.atomic_uint.2"_ns, 6u, 7u); } TEST(CallbackAndVarCacheOrder, AtomicUintReleaseAcquire) { RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_uint.3"), - NS_LITERAL_CSTRING("test_pref.atomic_uint.4"), 8u, 9u); + "test_pref.atomic_uint.3"_ns, "test_pref.atomic_uint.4"_ns, 8u, 9u); } TEST(CallbackAndVarCacheOrder, Float) { - RunTest(NS_LITERAL_CSTRING("test_pref.float.1"), - NS_LITERAL_CSTRING("test_pref.float.2"), -10.0f, 11.0f); + RunTest("test_pref.float.1"_ns, "test_pref.float.2"_ns, -10.0f, 11.0f); } TEST(CallbackAndVarCacheOrder, AtomicFloat) { - RunTest>( - NS_LITERAL_CSTRING("test_pref.atomic_float.1"), - NS_LITERAL_CSTRING("test_pref.atomic_float.2"), -12.0f, 13.0f); + RunTest>("test_pref.atomic_float.1"_ns, + "test_pref.atomic_float.2"_ns, -12.0f, + 13.0f); } } // namespace mozilla diff --git a/mozglue/tests/gtest/TestNativeNtGTest.cpp b/mozglue/tests/gtest/TestNativeNtGTest.cpp index b3eb488c2625..e0f0a343a74b 100644 --- a/mozglue/tests/gtest/TestNativeNtGTest.cpp +++ b/mozglue/tests/gtest/TestNativeNtGTest.cpp @@ -14,9 +14,7 @@ TEST(TestNativeNtGTest, GenerateDependentModuleSet) { mozilla::nt::PEHeaders executable(::GetModuleHandleW(nullptr)); auto dependentModules = executable.GenerateDependentModuleSet(); - EXPECT_NE(dependentModules.GetEntry(NS_LITERAL_STRING("mozglue.dll")), - nullptr); - EXPECT_NE(dependentModules.GetEntry(NS_LITERAL_STRING("MOZGLUE.dll")), - nullptr); - EXPECT_EQ(dependentModules.GetEntry(NS_LITERAL_STRING("xxx.dll")), nullptr); + EXPECT_NE(dependentModules.GetEntry(u"mozglue.dll"_ns), nullptr); + EXPECT_NE(dependentModules.GetEntry(u"MOZGLUE.dll"_ns), nullptr); + EXPECT_EQ(dependentModules.GetEntry(u"xxx.dll"_ns), nullptr); } diff --git a/netwerk/base/DefaultURI.cpp b/netwerk/base/DefaultURI.cpp index 2bdcd38745e9..1ace7e949d69 100644 --- a/netwerk/base/DefaultURI.cpp +++ b/netwerk/base/DefaultURI.cpp @@ -153,8 +153,7 @@ NS_IMETHODIMP DefaultURI::GetHost(nsACString& aHost) { // enclosed in brackets. Ideally we want to change that, but for the sake of // consitency we'll leave it like that for the moment. // Bug 1603199 should fix this. - if (StringBeginsWith(aHost, NS_LITERAL_CSTRING("[")) && - StringEndsWith(aHost, NS_LITERAL_CSTRING("]")) && + if (StringBeginsWith(aHost, "["_ns) && StringEndsWith(aHost, "]"_ns) && aHost.FindChar(':') != kNotFound) { aHost = Substring(aHost, 1, aHost.Length() - 2); } @@ -495,7 +494,7 @@ DefaultURI::Mutator::SetPathQueryRef(const nsACString& aPathQueryRef, } nsAutoCString pathQueryRef(aPathQueryRef); - if (!StringBeginsWith(pathQueryRef, NS_LITERAL_CSTRING("/"))) { + if (!StringBeginsWith(pathQueryRef, "/"_ns)) { pathQueryRef.Insert('/', 0); } diff --git a/netwerk/base/Predictor.cpp b/netwerk/base/Predictor.cpp index 5b03664ea0e0..adff0e6355b5 100644 --- a/netwerk/base/Predictor.cpp +++ b/netwerk/base/Predictor.cpp @@ -328,9 +328,9 @@ Predictor::GetInterface(const nsIID& iid, void** result) { static bool IsURIMetadataElement(const char* key) { return StringBeginsWith(nsDependentCString(key), - NS_LITERAL_CSTRING(META_DATA_PREFIX)) && - !NS_LITERAL_CSTRING(SEEN_META_DATA).Equals(key) && - !NS_LITERAL_CSTRING(RESOURCE_META_DATA).Equals(key); + nsLiteralCString(META_DATA_PREFIX)) && + !nsLiteralCString(SEEN_META_DATA).Equals(key) && + !nsLiteralCString(RESOURCE_META_DATA).Equals(key); } nsresult Predictor::OnMetaDataElement(const char* asciiKey, @@ -618,7 +618,7 @@ Predictor::PredictNative(nsIURI* targetURI, nsIURI* sourceURI, openFlags = nsICacheStorage::OPEN_READONLY | nsICacheStorage::OPEN_SECRETLY | nsICacheStorage::CHECK_MULTITHREADED; cacheDiskStorage->AsyncOpenURI(originKey, - NS_LITERAL_CSTRING(PREDICTOR_ORIGIN_EXTENSION), + nsLiteralCString(PREDICTOR_ORIGIN_EXTENSION), openFlags, originAction); PREDICTOR_LOG((" predict returning")); @@ -1405,7 +1405,7 @@ Predictor::LearnNative(nsIURI* targetURI, nsIURI* sourceURI, nsICacheStorage::CHECK_MULTITHREADED; } cacheDiskStorage->AsyncOpenURI(originKey, - NS_LITERAL_CSTRING(PREDICTOR_ORIGIN_EXTENSION), + nsLiteralCString(PREDICTOR_ORIGIN_EXTENSION), originOpenFlags, originAction); PREDICTOR_LOG(("Predictor::Learn returning")); @@ -1815,7 +1815,7 @@ Predictor::Resetter::OnMetaDataElement(const char* asciiKey, MOZ_ASSERT(NS_IsMainThread()); if (!StringBeginsWith(nsDependentCString(asciiKey), - NS_LITERAL_CSTRING(META_DATA_PREFIX))) { + nsLiteralCString(META_DATA_PREFIX))) { // Not a metadata entry we care about, carry on return NS_OK; } diff --git a/netwerk/base/ProxyAutoConfig.cpp b/netwerk/base/ProxyAutoConfig.cpp index 1412af5eb1a5..a06da99735dd 100644 --- a/netwerk/base/ProxyAutoConfig.cpp +++ b/netwerk/base/ProxyAutoConfig.cpp @@ -370,14 +370,14 @@ static void PACLogToConsole(nsString& aMessage) { // Javascript errors and warnings are logged to the main error console static void PACLogErrorOrWarning(const nsAString& aKind, JSErrorReport* aReport) { - nsString formattedMessage(NS_LITERAL_STRING("PAC Execution ")); + nsString formattedMessage(u"PAC Execution "_ns); formattedMessage += aKind; - formattedMessage += NS_LITERAL_STRING(": "); + formattedMessage += u": "_ns; if (aReport->message()) formattedMessage.Append(NS_ConvertUTF8toUTF16(aReport->message().c_str())); - formattedMessage += NS_LITERAL_STRING(" ["); + formattedMessage += u" ["_ns; formattedMessage.Append(aReport->linebuf(), aReport->linebufLength()); - formattedMessage += NS_LITERAL_STRING("]"); + formattedMessage += u"]"_ns; PACLogToConsole(formattedMessage); } @@ -385,7 +385,7 @@ static void PACWarningReporter(JSContext* aCx, JSErrorReport* aReport) { MOZ_ASSERT(aReport); MOZ_ASSERT(aReport->isWarning()); - PACLogErrorOrWarning(NS_LITERAL_STRING("Warning"), aReport); + PACLogErrorOrWarning(u"Warning"_ns, aReport); } class MOZ_STACK_CLASS AutoPACErrorReporter { @@ -408,7 +408,7 @@ class MOZ_STACK_CLASS AutoPACErrorReporter { return; } - PACLogErrorOrWarning(NS_LITERAL_STRING("Error"), report.report()); + PACLogErrorOrWarning(u"Error"_ns, report.report()); } }; @@ -768,10 +768,9 @@ nsresult ProxyAutoConfig::SetupJS() { JS::Rooted script(cx, CompilePACScript(cx)); if (!script || !JS_ExecuteScript(cx, script)) { - nsString alertMessage( - NS_LITERAL_STRING("PAC file failed to install from ")); + nsString alertMessage(u"PAC file failed to install from "_ns); if (isDataURI) { - alertMessage += NS_LITERAL_STRING("data: URI"); + alertMessage += u"data: URI"_ns; } else { alertMessage += NS_ConvertUTF8toUTF16(mPACURI); } @@ -782,9 +781,9 @@ nsresult ProxyAutoConfig::SetupJS() { SetRunning(nullptr); mJSContext->SetOK(); - nsString alertMessage(NS_LITERAL_STRING("PAC file installed from ")); + nsString alertMessage(u"PAC file installed from "_ns); if (isDataURI) { - alertMessage += NS_LITERAL_STRING("data: URI"); + alertMessage += u"data: URI"_ns; } else { alertMessage += NS_ConvertUTF8toUTF16(mPACURI); } diff --git a/netwerk/base/mozurl/MozURL.h b/netwerk/base/mozurl/MozURL.h index a05c2710dd3d..e48a0203cf93 100644 --- a/netwerk/base/mozurl/MozURL.h +++ b/netwerk/base/mozurl/MozURL.h @@ -106,8 +106,8 @@ class MozURL final { // chain setter operations as such: // // RefPtr url2; - // nsresult rv = url->Mutate().SetHostname(NS_LITERAL_CSTRING("newhost")) - // .SetFilePath(NS_LITERAL_CSTRING("new/file/path")) + // nsresult rv = url->Mutate().SetHostname("newhost"_ns) + // .SetFilePath("new/file/path"_ns) // .Finalize(getter_AddRefs(url2)); // if (NS_SUCCEEDED(rv)) { /* use url2 */ } Mutator& SetScheme(const nsACString& aScheme) { diff --git a/netwerk/base/nsINetworkInterceptController.idl b/netwerk/base/nsINetworkInterceptController.idl index 3a33cd7f9abf..64a4a71b03b2 100644 --- a/netwerk/base/nsINetworkInterceptController.idl +++ b/netwerk/base/nsINetworkInterceptController.idl @@ -200,24 +200,24 @@ interface nsIInterceptedChannel : nsISupports case nsIContentPolicy::TYPE_INTERNAL_MODULE: case nsIContentPolicy::TYPE_INTERNAL_MODULE_PRELOAD: case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS: { - aKey = NS_LITERAL_CSTRING("subresource-script"); + aKey = "subresource-script"_ns; break; } case nsIContentPolicy::TYPE_IMAGE: case nsIContentPolicy::TYPE_INTERNAL_IMAGE: case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD: case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON: { - aKey = NS_LITERAL_CSTRING("subresource-image"); + aKey = "subresource-image"_ns; break; } case nsIContentPolicy::TYPE_STYLESHEET: case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET: case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD: { - aKey = NS_LITERAL_CSTRING("subresource-stylesheet"); + aKey = "subresource-stylesheet"_ns; break; } default: { - aKey = NS_LITERAL_CSTRING("subresource-other"); + aKey = "subresource-other"_ns; break; } } diff --git a/netwerk/base/nsIOService.cpp b/netwerk/base/nsIOService.cpp index 79abb1310f2a..465a647efa5f 100644 --- a/netwerk/base/nsIOService.cpp +++ b/netwerk/base/nsIOService.cpp @@ -271,13 +271,11 @@ nsresult nsIOService::Init() { PrefsChanged(); mSocketProcessTopicBlackList.PutEntry( - NS_LITERAL_CSTRING(NS_XPCOM_WILL_SHUTDOWN_OBSERVER_ID)); + nsLiteralCString(NS_XPCOM_WILL_SHUTDOWN_OBSERVER_ID)); mSocketProcessTopicBlackList.PutEntry( - NS_LITERAL_CSTRING(NS_XPCOM_SHUTDOWN_OBSERVER_ID)); - mSocketProcessTopicBlackList.PutEntry( - NS_LITERAL_CSTRING("xpcom-shutdown-threads")); - mSocketProcessTopicBlackList.PutEntry( - NS_LITERAL_CSTRING("profile-do-change")); + nsLiteralCString(NS_XPCOM_SHUTDOWN_OBSERVER_ID)); + mSocketProcessTopicBlackList.PutEntry("xpcom-shutdown-threads"_ns); + mSocketProcessTopicBlackList.PutEntry("profile-do-change"_ns); // Register for profile change notifications mObserverService = services::GetObserverService(); @@ -850,9 +848,8 @@ nsresult nsIOService::GetCachedProtocolHandler(const char* scheme, } static bool UsesExternalProtocolHandler(const char* aScheme) { - if (NS_LITERAL_CSTRING("file").Equals(aScheme) || - NS_LITERAL_CSTRING("chrome").Equals(aScheme) || - NS_LITERAL_CSTRING("resource").Equals(aScheme)) { + if ("file"_ns.Equals(aScheme) || "chrome"_ns.Equals(aScheme) || + "resource"_ns.Equals(aScheme)) { // Don't allow file:, chrome: or resource: URIs to be handled with // nsExternalProtocolHandler, since internally we rely on being able to // use and read from these URIs. @@ -861,7 +858,7 @@ static bool UsesExternalProtocolHandler(const char* aScheme) { // When ftp protocol is disabled, return true if external protocol handler was // not explicitly disabled by the prererence. - if (NS_LITERAL_CSTRING("ftp").Equals(aScheme) && + if ("ftp"_ns.Equals(aScheme) && !Preferences::GetBool("network.ftp.enabled", true) && Preferences::GetBool("network.protocol-handler.external.ftp", true)) { return true; @@ -1605,7 +1602,7 @@ nsIOService::Observe(nsISupports* subject, const char* topic, SetOffline(false); } } else if (!strcmp(topic, kProfileDoChange)) { - if (data && NS_LITERAL_STRING("startup").Equals(data)) { + if (data && u"startup"_ns.Equals(data)) { // Lazy initialization of network link service (see bug 620472) InitializeNetworkLinkService(); // Set up the initilization flag regardless the actuall result. diff --git a/netwerk/base/nsIncrementalDownload.cpp b/netwerk/base/nsIncrementalDownload.cpp index 2f351a8f6322..2c54ddadf1d3 100644 --- a/netwerk/base/nsIncrementalDownload.cpp +++ b/netwerk/base/nsIncrementalDownload.cpp @@ -240,12 +240,11 @@ nsresult nsIncrementalDownload::ProcessTimeout() { nsAutoCString range; MakeRangeSpec(mCurrentSize, mTotalSize, mChunkSize, mInterval == 0, range); - rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Range"), range, false); + rv = http->SetRequestHeader("Range"_ns, range, false); if (NS_FAILED(rv)) return rv; if (!mPartialValidator.IsEmpty()) { - rv = http->SetRequestHeader(NS_LITERAL_CSTRING("If-Range"), - mPartialValidator, false); + rv = http->SetRequestHeader("If-Range"_ns, mPartialValidator, false); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::ProcessTimeout\n" @@ -254,15 +253,13 @@ nsresult nsIncrementalDownload::ProcessTimeout() { } if (mCacheBust) { - rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"), - NS_LITERAL_CSTRING("no-cache"), false); + rv = http->SetRequestHeader("Cache-Control"_ns, "no-cache"_ns, false); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::ProcessTimeout\n" " failed to set request header: If-Range\n")); } - rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Pragma"), - NS_LITERAL_CSTRING("no-cache"), false); + rv = http->SetRequestHeader("Pragma"_ns, "no-cache"_ns, false); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::ProcessTimeout\n" @@ -528,7 +525,7 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { int64_t startByte = 0; bool confirmedOK = false; - rv = http->GetResponseHeader(NS_LITERAL_CSTRING("Content-Range"), buf); + rv = http->GetResponseHeader("Content-Range"_ns, buf); if (NS_FAILED(rv)) return rv; // it isn't a useful 206 without a CONTENT-RANGE of some // sort @@ -584,13 +581,11 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { // Update knowledge of mFinalURI rv = http->GetURI(getter_AddRefs(mFinalURI)); if (NS_FAILED(rv)) return rv; - Unused << http->GetResponseHeader(NS_LITERAL_CSTRING("Etag"), - mPartialValidator); - if (StringBeginsWith(mPartialValidator, NS_LITERAL_CSTRING("W/"))) + Unused << http->GetResponseHeader("Etag"_ns, mPartialValidator); + if (StringBeginsWith(mPartialValidator, "W/"_ns)) mPartialValidator.Truncate(); // don't use weak validators if (mPartialValidator.IsEmpty()) { - rv = http->GetResponseHeader(NS_LITERAL_CSTRING("Last-Modified"), - mPartialValidator); + rv = http->GetResponseHeader("Last-Modified"_ns, mPartialValidator); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::OnStartRequest\n" @@ -602,7 +597,7 @@ nsIncrementalDownload::OnStartRequest(nsIRequest* request) { // OK, read the Content-Range header to determine the total size of this // download file. nsAutoCString buf; - rv = http->GetResponseHeader(NS_LITERAL_CSTRING("Content-Range"), buf); + rv = http->GetResponseHeader("Content-Range"_ns, buf); if (NS_FAILED(rv)) return rv; int32_t slash = buf.FindChar('/'); if (slash == kNotFound) { @@ -745,8 +740,7 @@ nsresult nsIncrementalDownload::ClearRequestHeader(nsIHttpChannel* channel) { // We don't support encodings -- they make the Content-Length not equal // to the actual size of the data. - return channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Encoding"), - NS_LITERAL_CSTRING(""), false); + return channel->SetRequestHeader("Accept-Encoding"_ns, ""_ns, false); } // nsIChannelEventSink @@ -781,16 +775,14 @@ nsIncrementalDownload::AsyncOnChannelRedirect( mPartialValidator.Truncate(); if (mCacheBust) { - rv = - newHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"), - NS_LITERAL_CSTRING("no-cache"), false); + rv = newHttpChannel->SetRequestHeader("Cache-Control"_ns, "no-cache"_ns, + false); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::AsyncOnChannelRedirect\n" " failed to set request header: Cache-Control\n")); } - rv = newHttpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Pragma"), NS_LITERAL_CSTRING("no-cache"), false); + rv = newHttpChannel->SetRequestHeader("Pragma"_ns, "no-cache"_ns, false); if (NS_FAILED(rv)) { LOG( ("nsIncrementalDownload::AsyncOnChannelRedirect\n" diff --git a/netwerk/base/nsMediaFragmentURIParser.cpp b/netwerk/base/nsMediaFragmentURIParser.cpp index 8091fd93b125..7d81ff7e24a8 100644 --- a/netwerk/base/nsMediaFragmentURIParser.cpp +++ b/netwerk/base/nsMediaFragmentURIParser.cpp @@ -289,10 +289,10 @@ bool nsMediaFragmentURIParser::ParseXYWH(nsDependentSubstring aString) { ClipUnit clipUnit; // Determine units. - if (StringBeginsWith(aString, NS_LITERAL_STRING("pixel:"))) { + if (StringBeginsWith(aString, u"pixel:"_ns)) { clipUnit = eClipUnit_Pixel; aString.Rebind(aString, 6); - } else if (StringBeginsWith(aString, NS_LITERAL_STRING("percent:"))) { + } else if (StringBeginsWith(aString, u"percent:"_ns)) { clipUnit = eClipUnit_Percent; aString.Rebind(aString, 8); } else { diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp index dc4211403550..f3ec51c8c43c 100644 --- a/netwerk/base/nsNetUtil.cpp +++ b/netwerk/base/nsNetUtil.cpp @@ -767,7 +767,7 @@ nsresult NS_NewInputStreamChannelInternal(nsIChannel** outChannel, nsIURI* aUri, nsCOMPtr channel; rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aUri, stream.forget(), aContentType, - NS_LITERAL_CSTRING("UTF-8"), aLoadInfo); + "UTF-8"_ns, aLoadInfo); NS_ENSURE_SUCCESS(rv, rv); @@ -1150,7 +1150,7 @@ void NS_GetReferrerFromChannel(nsIChannel* channel, nsIURI** referrer) { // referrer may be empty for security reasons (for example, when loading // an http page with an https referrer). nsresult rv = props->GetPropertyAsInterface( - NS_LITERAL_STRING("docshell.internalReferrer"), NS_GET_IID(nsIURI), + u"docshell.internalReferrer"_ns, NS_GET_IID(nsIURI), reinterpret_cast(referrer)); if (NS_SUCCEEDED(rv)) { return; @@ -2714,8 +2714,7 @@ void NS_SniffContent(const char* aSnifferType, nsIRequest* aRequest, */ nsAutoCString currentContentType; channel->GetContentType(currentContentType); - if (!StringBeginsWith(currentContentType, - NS_LITERAL_CSTRING("application/"))) { + if (!StringBeginsWith(currentContentType, "application/"_ns)) { return; } } @@ -2796,8 +2795,8 @@ nsresult NS_ShouldSecureUpgrade( EmptyString(), // aScriptSample 0, // aLineNumber 0, // aColumnNumber - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("upgradeInsecureRequest"), innerWindowId, + nsIScriptError::warningFlag, "upgradeInsecureRequest"_ns, + innerWindowId, !!aLoadInfo->GetOriginAttributes().mPrivateBrowsingId); Telemetry::AccumulateCategorical( Telemetry::LABELS_HTTP_SCHEME_UPGRADE_TYPE::CSP); @@ -2815,8 +2814,7 @@ nsresult NS_ShouldSecureUpgrade( AutoTArray params = {brandName, reportSpec, reportScheme}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("DATA_URI_BLOCKED"), doc, + nsIScriptError::warningFlag, "DATA_URI_BLOCKED"_ns, doc, nsContentUtils::eSECURITY_PROPERTIES, "BrowserUpgradeInsecureDisplayRequest", params); } @@ -2926,8 +2924,7 @@ nsresult NS_ShouldSecureUpgrade( nsresult NS_GetSecureUpgradedURI(nsIURI* aURI, nsIURI** aUpgradedURI) { NS_MutateURI mutator(aURI); - mutator.SetScheme( - NS_LITERAL_CSTRING("https")); // Change the scheme to HTTPS: + mutator.SetScheme("https"_ns); // Change the scheme to HTTPS: // Change the default port to 443: nsCOMPtr stdURL = do_QueryInterface(aURI); diff --git a/netwerk/base/nsProtocolProxyService.cpp b/netwerk/base/nsProtocolProxyService.cpp index e33c2469717f..5a7d3e71c2e5 100644 --- a/netwerk/base/nsProtocolProxyService.cpp +++ b/netwerk/base/nsProtocolProxyService.cpp @@ -325,7 +325,7 @@ class nsAsyncResolveRequest final : public nsIRunnable, // If the PAC service is not avail (e.g. failed pac load // or shutdown) then we will be going direct. Make that // mapping now so that any filters are still applied. - mPACString = NS_LITERAL_CSTRING("DIRECT;"); + mPACString = "DIRECT;"_ns; mStatus = NS_OK; LOG(("pac not available, use DIRECT\n")); diff --git a/netwerk/base/nsSimpleURI.cpp b/netwerk/base/nsSimpleURI.cpp index 6a286433c411..b4a7d50cd140 100644 --- a/netwerk/base/nsSimpleURI.cpp +++ b/netwerk/base/nsSimpleURI.cpp @@ -199,15 +199,13 @@ bool nsSimpleURI::Deserialize(const URIParams& aParams) { NS_IMETHODIMP nsSimpleURI::GetSpec(nsACString& result) { - if (!result.Assign(mScheme, fallible) || - !result.Append(NS_LITERAL_CSTRING(":"), fallible) || + if (!result.Assign(mScheme, fallible) || !result.Append(":"_ns, fallible) || !result.Append(mPath, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } if (mIsQueryValid) { - if (!result.Append(NS_LITERAL_CSTRING("?"), fallible) || - !result.Append(mQuery, fallible)) { + if (!result.Append("?"_ns, fallible) || !result.Append(mQuery, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } } else { @@ -215,8 +213,7 @@ nsSimpleURI::GetSpec(nsACString& result) { } if (mIsRefValid) { - if (!result.Append(NS_LITERAL_CSTRING("#"), fallible) || - !result.Append(mRef, fallible)) { + if (!result.Append("#"_ns, fallible) || !result.Append(mRef, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } } else { @@ -229,9 +226,9 @@ nsSimpleURI::GetSpec(nsACString& result) { // result may contain unescaped UTF-8 characters NS_IMETHODIMP nsSimpleURI::GetSpecIgnoringRef(nsACString& result) { - result = mScheme + NS_LITERAL_CSTRING(":") + mPath; + result = mScheme + ":"_ns + mPath; if (mIsQueryValid) { - result += NS_LITERAL_CSTRING("?") + mQuery; + result += "?"_ns + mQuery; } return NS_OK; } @@ -301,7 +298,7 @@ nsresult nsSimpleURI::SetScheme(const nsACString& scheme) { NS_IMETHODIMP nsSimpleURI::GetPrePath(nsACString& result) { - result = mScheme + NS_LITERAL_CSTRING(":"); + result = mScheme + ":"_ns; return NS_OK; } @@ -362,10 +359,10 @@ NS_IMETHODIMP nsSimpleURI::GetPathQueryRef(nsACString& result) { result = mPath; if (mIsQueryValid) { - result += NS_LITERAL_CSTRING("?") + mQuery; + result += "?"_ns + mQuery; } if (mIsRefValid) { - result += NS_LITERAL_CSTRING("#") + mRef; + result += "#"_ns + mRef; } return NS_OK; diff --git a/netwerk/base/nsSocketTransport2.cpp b/netwerk/base/nsSocketTransport2.cpp index 970078b5875e..51b8a8f8b356 100644 --- a/netwerk/base/nsSocketTransport2.cpp +++ b/netwerk/base/nsSocketTransport2.cpp @@ -1328,7 +1328,7 @@ nsresult nsSocketTransport::InitiateSocket() { netAddrCString.SetLength(kIPv6CStrBufSize); if (!NetAddrToString(&mNetAddr, netAddrCString.BeginWriting(), kIPv6CStrBufSize)) - netAddrCString = NS_LITERAL_CSTRING(""); + netAddrCString = ""_ns; SOCKET_LOG( ("nsSocketTransport::InitiateSocket skipping " "speculative connection for host [%s:%d] proxy " diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index 634d9f9bf9f4..d27e5f62ba64 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -944,8 +944,7 @@ nsSocketTransportService::CreateTransport(const nsTArray& types, const nsACString& host, int32_t port, nsIProxyInfo* proxyInfo, nsISocketTransport** result) { - return CreateRoutedTransport(types, host, port, NS_LITERAL_CSTRING(""), 0, - proxyInfo, result); + return CreateRoutedTransport(types, host, port, ""_ns, 0, proxyInfo, result); } NS_IMETHODIMP diff --git a/netwerk/base/nsStandardURL.cpp b/netwerk/base/nsStandardURL.cpp index df4188b5004b..aed6e97e2715 100644 --- a/netwerk/base/nsStandardURL.cpp +++ b/netwerk/base/nsStandardURL.cpp @@ -1375,7 +1375,7 @@ nsStandardURL::GetDisplayHostPort(nsACString& aUnicodeHostPort) { return rv; } - if (StringBeginsWith(Hostport(), NS_LITERAL_CSTRING("["))) { + if (StringBeginsWith(Hostport(), "["_ns)) { aUnicodeHostPort.AssignLiteral("["); aUnicodeHostPort.Append(unicodeHostPort); aUnicodeHostPort.AppendLiteral("]"); @@ -1797,7 +1797,7 @@ nsresult nsStandardURL::SetUsername(const nsACString& input) { if (mUsername.mLen < 0 && mPassword.mLen < 0) { MOZ_ASSERT(!escUsername.IsEmpty(), "Should not be empty at this point"); mUsername.mPos = mAuthority.mPos; - mSpec.Insert(escUsername + NS_LITERAL_CSTRING("@"), mUsername.mPos); + mSpec.Insert(escUsername + "@"_ns, mUsername.mPos); shift = escUsername.Length() + 1; mUsername.mLen = escUsername.Length() > 0 ? escUsername.Length() : -1; } else { @@ -1877,13 +1877,11 @@ nsresult nsStandardURL::SetPassword(const nsACString& input) { if (mPassword.mLen < 0) { if (mUsername.mLen > 0) { mPassword.mPos = mUsername.mPos + mUsername.mLen + 1; - mSpec.Insert(NS_LITERAL_CSTRING(":") + escPassword, mPassword.mPos - 1); + mSpec.Insert(":"_ns + escPassword, mPassword.mPos - 1); shift = escPassword.Length() + 1; } else { mPassword.mPos = mAuthority.mPos + 1; - mSpec.Insert( - NS_LITERAL_CSTRING(":") + escPassword + NS_LITERAL_CSTRING("@"), - mPassword.mPos - 1); + mSpec.Insert(":"_ns + escPassword + "@"_ns, mPassword.mPos - 1); shift = escPassword.Length() + 2; } } else { @@ -2538,8 +2536,7 @@ nsStandardURL::Resolve(const nsACString& in, nsACString& out) { break; default: if (coalesceFlag & NET_COALESCE_DOUBLE_SLASH_IS_ROOT) { - if (Filename().Equals(NS_LITERAL_CSTRING("%2F"), - nsCaseInsensitiveCStringComparator)) { + if (Filename().Equals("%2F"_ns, nsCaseInsensitiveCStringComparator)) { // if ftp URL ends with %2F then simply // append relative part because %2F also // marks the root directory with ftp-urls diff --git a/netwerk/base/nsStreamTransportService.cpp b/netwerk/base/nsStreamTransportService.cpp index 6e0a7b9d7a71..8a528df2d625 100644 --- a/netwerk/base/nsStreamTransportService.cpp +++ b/netwerk/base/nsStreamTransportService.cpp @@ -251,7 +251,7 @@ nsresult nsStreamTransportService::Init() { mPool = new nsThreadPool(); // Configure the pool - mPool->SetName(NS_LITERAL_CSTRING("StreamTrans")); + mPool->SetName("StreamTrans"_ns); mPool->SetThreadLimit(25); mPool->SetIdleThreadLimit(5); mPool->SetIdleThreadTimeoutRegressive(true); diff --git a/netwerk/cache/nsCacheService.cpp b/netwerk/cache/nsCacheService.cpp index 12c8c5f59fcf..5b2fa139a8a4 100644 --- a/netwerk/cache/nsCacheService.cpp +++ b/netwerk/cache/nsCacheService.cpp @@ -554,7 +554,7 @@ void nsCacheService::Shutdown() { if (cacheIOThread) nsShutdownThread::BlockingShutdown(cacheIOThread); if (shouldSanitize) { - nsresult rv = parentDir->AppendNative(NS_LITERAL_CSTRING("Cache")); + nsresult rv = parentDir->AppendNative("Cache"_ns); if (NS_SUCCEEDED(rv)) { bool exists; if (NS_SUCCEEDED(parentDir->Exists(&exists)) && exists) @@ -1800,7 +1800,7 @@ void nsCacheService::GetDiskCacheDirectory(nsIFile** result) { GetCacheBaseDirectoty(getter_AddRefs(directory)); if (!directory) return; - nsresult rv = directory->AppendNative(NS_LITERAL_CSTRING("Cache")); + nsresult rv = directory->AppendNative("Cache"_ns); if (NS_FAILED(rv)) return; directory.forget(result); @@ -1812,7 +1812,7 @@ void nsCacheService::GetAppCacheDirectory(nsIFile** result) { GetCacheBaseDirectoty(getter_AddRefs(directory)); if (!directory) return; - nsresult rv = directory->AppendNative(NS_LITERAL_CSTRING("OfflineCache")); + nsresult rv = directory->AppendNative("OfflineCache"_ns); if (NS_FAILED(rv)) return; directory.forget(result); diff --git a/netwerk/cache/nsDiskCacheDeviceSQL.cpp b/netwerk/cache/nsDiskCacheDeviceSQL.cpp index 9d56a00cc55a..2e7d44246735 100644 --- a/netwerk/cache/nsDiskCacheDeviceSQL.cpp +++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp @@ -109,15 +109,15 @@ class EvictionObserver { : mDB(db), mEvictionFunction(evictionFunction) { mEvictionFunction->Init(); mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TEMP TRIGGER cache_on_delete BEFORE DELETE" - " ON moz_cache FOR EACH ROW BEGIN SELECT" - " cache_eviction_observer(" - " OLD.ClientID, OLD.key, OLD.generation);" - " END;")); + nsLiteralCString("CREATE TEMP TRIGGER cache_on_delete BEFORE DELETE" + " ON moz_cache FOR EACH ROW BEGIN SELECT" + " cache_eviction_observer(" + " OLD.ClientID, OLD.key, OLD.generation);" + " END;")); } ~EvictionObserver() { - mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DROP TRIGGER cache_on_delete;")); + mDB->ExecuteSimpleSQL("DROP TRIGGER cache_on_delete;"_ns); mEvictionFunction->Reset(); } @@ -423,7 +423,7 @@ nsOfflineCacheBinding* nsOfflineCacheBinding::Create(nsIFile* cacheDir, char leaf[64]; if (generation == -1) { - file->AppendNative(NS_LITERAL_CSTRING("placeholder")); + file->AppendNative("placeholder"_ns); for (generation = 0;; ++generation) { SprintfLiteral(leaf, "%014" PRIX64 "-%X", hash, generation); @@ -1056,7 +1056,7 @@ nsresult nsOfflineCacheDevice::InitWithSqlite(mozIStorageService* ss) { nsCOMPtr indexFile; rv = mCacheDirectory->Clone(getter_AddRefs(indexFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = indexFile->AppendNative(NS_LITERAL_CSTRING("index.sqlite")); + rv = indexFile->AppendNative("index.sqlite"_ns); NS_ENSURE_SUCCESS(rv, rv); MOZ_ASSERT(ss, @@ -1069,7 +1069,7 @@ nsresult nsOfflineCacheDevice::InitWithSqlite(mozIStorageService* ss) { mInitEventTarget = GetCurrentEventTarget(); - mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF;")); + mDB->ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns); // XXX ... other initialization steps @@ -1081,37 +1081,37 @@ nsresult nsOfflineCacheDevice::InitWithSqlite(mozIStorageService* ss) { // "Generation" is the data file generation number. // rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS moz_cache (\n" - " ClientID TEXT,\n" - " Key TEXT,\n" - " MetaData BLOB,\n" - " Generation INTEGER,\n" - " DataSize INTEGER,\n" - " FetchCount INTEGER,\n" - " LastFetched INTEGER,\n" - " LastModified INTEGER,\n" - " ExpirationTime INTEGER,\n" - " ItemType INTEGER DEFAULT 0\n" - ");\n")); + nsLiteralCString("CREATE TABLE IF NOT EXISTS moz_cache (\n" + " ClientID TEXT,\n" + " Key TEXT,\n" + " MetaData BLOB,\n" + " Generation INTEGER,\n" + " DataSize INTEGER,\n" + " FetchCount INTEGER,\n" + " LastFetched INTEGER,\n" + " LastModified INTEGER,\n" + " ExpirationTime INTEGER,\n" + " ItemType INTEGER DEFAULT 0\n" + ");\n")); NS_ENSURE_SUCCESS(rv, rv); // Databases from 1.9.0 don't have the ItemType column. Add the column // here, but don't worry about failures (the column probably already exists) - mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "ALTER TABLE moz_cache ADD ItemType INTEGER DEFAULT 0")); + mDB->ExecuteSimpleSQL( + "ALTER TABLE moz_cache ADD ItemType INTEGER DEFAULT 0"_ns); // Create the table for storing cache groups. All actions on // moz_cache_groups use the GroupID, so use it as the primary key. rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS moz_cache_groups (\n" - " GroupID TEXT PRIMARY KEY,\n" - " ActiveClientID TEXT\n" - ");\n")); + nsLiteralCString("CREATE TABLE IF NOT EXISTS moz_cache_groups (\n" + " GroupID TEXT PRIMARY KEY,\n" + " ActiveClientID TEXT\n" + ");\n")); NS_ENSURE_SUCCESS(rv, rv); mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_cache_groups " - "ADD ActivateTimeStamp INTEGER DEFAULT 0")); + nsLiteralCString("ALTER TABLE moz_cache_groups " + "ADD ActivateTimeStamp INTEGER DEFAULT 0")); // ClientID: clientID joining moz_cache and moz_cache_namespaces // tables. @@ -1119,48 +1119,46 @@ nsresult nsOfflineCacheDevice::InitWithSqlite(mozIStorageService* ss) { // for fallback entries). // ItemType: the type of namespace. rv = - mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING("CREATE TABLE IF NOT EXISTS" - " moz_cache_namespaces (\n" - " ClientID TEXT,\n" - " NameSpace TEXT,\n" - " Data TEXT,\n" - " ItemType INTEGER\n" - ");\n")); + mDB->ExecuteSimpleSQL(nsLiteralCString("CREATE TABLE IF NOT EXISTS" + " moz_cache_namespaces (\n" + " ClientID TEXT,\n" + " NameSpace TEXT,\n" + " Data TEXT,\n" + " ItemType INTEGER\n" + ");\n")); NS_ENSURE_SUCCESS(rv, rv); // Databases from 1.9.0 have a moz_cache_index that should be dropped - rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX IF EXISTS moz_cache_index")); + rv = mDB->ExecuteSimpleSQL("DROP INDEX IF EXISTS moz_cache_index"_ns); NS_ENSURE_SUCCESS(rv, rv); // Key/ClientID pairs should be unique in the database. All queries // against moz_cache use the Key (which is also the most unique), so // use it as the primary key for this index. rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE UNIQUE INDEX IF NOT EXISTS " - " moz_cache_key_clientid_index" - " ON moz_cache (Key, ClientID);")); + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS " + " moz_cache_key_clientid_index" + " ON moz_cache (Key, ClientID);")); NS_ENSURE_SUCCESS(rv, rv); // Used for ClientID lookups and to keep ClientID/NameSpace pairs unique. rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE UNIQUE INDEX IF NOT EXISTS" - " moz_cache_namespaces_clientid_index" - " ON moz_cache_namespaces (ClientID, NameSpace);")); + nsLiteralCString("CREATE UNIQUE INDEX IF NOT EXISTS" + " moz_cache_namespaces_clientid_index" + " ON moz_cache_namespaces (ClientID, NameSpace);")); NS_ENSURE_SUCCESS(rv, rv); // Used for namespace lookups. rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX IF NOT EXISTS" - " moz_cache_namespaces_namespace_index" - " ON moz_cache_namespaces (NameSpace);")); + nsLiteralCString("CREATE INDEX IF NOT EXISTS" + " moz_cache_namespaces_namespace_index" + " ON moz_cache_namespaces (NameSpace);")); NS_ENSURE_SUCCESS(rv, rv); mEvictionFunction = new nsOfflineCacheEvictionFunction(this); if (!mEvictionFunction) return NS_ERROR_OUT_OF_MEMORY; - rv = mDB->CreateFunction(NS_LITERAL_CSTRING("cache_eviction_observer"), 3, - mEvictionFunction); + rv = mDB->CreateFunction("cache_eviction_observer"_ns, 3, mEvictionFunction); NS_ENSURE_SUCCESS(rv, rv); // create all (most) of our statements up front @@ -1293,7 +1291,7 @@ nsresult nsOfflineCacheDevice::Shutdown() { EvictionObserver evictionObserver(mDB, mEvictionFunction); // Delete all rows whose clientID is not an active clientID. - nsresult rv = mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = mDB->ExecuteSimpleSQL(nsLiteralCString( "DELETE FROM moz_cache WHERE rowid IN" " (SELECT moz_cache.rowid FROM" " moz_cache LEFT OUTER JOIN moz_cache_groups ON" @@ -1306,7 +1304,7 @@ nsresult nsOfflineCacheDevice::Shutdown() { evictionObserver.Apply(); // Delete all namespaces whose clientID is not an active clientID. - rv = mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mDB->ExecuteSimpleSQL(nsLiteralCString( "DELETE FROM moz_cache_namespaces WHERE rowid IN" " (SELECT moz_cache_namespaces.rowid FROM" " moz_cache_namespaces LEFT OUTER JOIN moz_cache_groups ON" @@ -1712,7 +1710,7 @@ nsresult nsOfflineCacheDevice::Visit(nsICacheVisitor* visitor) { // XXX may want to list columns explicitly nsCOMPtr statement; - rv = mDB->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM moz_cache;"), + rv = mDB->CreateStatement("SELECT * FROM moz_cache;"_ns, getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); @@ -1756,9 +1754,8 @@ nsresult nsOfflineCacheDevice::EvictEntries(const char* clientID) { nsCOMPtr statement; nsresult rv; if (clientID) { - rv = mDB->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cache WHERE ClientID=?;"), - getter_AddRefs(statement)); + rv = mDB->CreateStatement("DELETE FROM moz_cache WHERE ClientID=?;"_ns, + getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID)); @@ -1768,7 +1765,7 @@ nsresult nsOfflineCacheDevice::EvictEntries(const char* clientID) { NS_ENSURE_SUCCESS(rv, rv); rv = mDB->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "DELETE FROM moz_cache_groups WHERE ActiveClientID=?;"), getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); @@ -1782,16 +1779,15 @@ nsresult nsOfflineCacheDevice::EvictEntries(const char* clientID) { // TODO - Should update internal hashtables. // Low priority, since this API is not widely used. } else { - rv = mDB->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM moz_cache;"), + rv = mDB->CreateStatement("DELETE FROM moz_cache;"_ns, getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); NS_ENSURE_SUCCESS(rv, rv); - rv = mDB->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cache_groups;"), - getter_AddRefs(statement)); + rv = mDB->CreateStatement("DELETE FROM moz_cache_groups;"_ns, + getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -1809,16 +1805,15 @@ nsresult nsOfflineCacheDevice::EvictEntries(const char* clientID) { // Also evict any namespaces associated with this clientID. if (clientID) { rv = mDB->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cache_namespaces WHERE ClientID=?"), + "DELETE FROM moz_cache_namespaces WHERE ClientID=?"_ns, getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); rv = statement->BindUTF8StringByIndex(0, nsDependentCString(clientID)); NS_ENSURE_SUCCESS(rv, rv); } else { - rv = mDB->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cache_namespaces;"), - getter_AddRefs(statement)); + rv = mDB->CreateStatement("DELETE FROM moz_cache_namespaces;"_ns, + getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); } @@ -2300,7 +2295,7 @@ OriginMatch::OnFunctionCall(mozIStorageValueArray* aFunctionArguments, rv = aFunctionArguments->GetUTF8String(0, groupId); NS_ENSURE_SUCCESS(rv, rv); - int32_t hash = groupId.Find(NS_LITERAL_CSTRING("#")); + int32_t hash = groupId.Find("#"_ns); if (hash == kNotFound) { // Just ignore... return NS_OK; @@ -2334,23 +2329,21 @@ nsresult nsOfflineCacheDevice::Evict( nsresult rv; nsCOMPtr function1(new OriginMatch(aPattern)); - rv = mDB->CreateFunction(NS_LITERAL_CSTRING("ORIGIN_MATCH"), 1, function1); + rv = mDB->CreateFunction("ORIGIN_MATCH"_ns, 1, function1); NS_ENSURE_SUCCESS(rv, rv); class AutoRemoveFunc { public: mozIStorageConnection* mDB; explicit AutoRemoveFunc(mozIStorageConnection* aDB) : mDB(aDB) {} - ~AutoRemoveFunc() { - mDB->RemoveFunction(NS_LITERAL_CSTRING("ORIGIN_MATCH")); - } + ~AutoRemoveFunc() { mDB->RemoveFunction("ORIGIN_MATCH"_ns); } }; AutoRemoveFunc autoRemove(mDB); nsCOMPtr statement; rv = mDB->CreateStatement( - NS_LITERAL_CSTRING("SELECT GroupID, ActiveClientID FROM moz_cache_groups " - "WHERE ORIGIN_MATCH(GroupID);"), + nsLiteralCString("SELECT GroupID, ActiveClientID FROM moz_cache_groups " + "WHERE ORIGIN_MATCH(GroupID);"), getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); @@ -2585,7 +2578,7 @@ void nsOfflineCacheDevice::SetCacheParentDirectory(nsIFile* parentDir) { nsCOMPtr dir; rv = parentDir->Clone(getter_AddRefs(dir)); if (NS_FAILED(rv)) return; - rv = dir->AppendNative(NS_LITERAL_CSTRING("OfflineCache")); + rv = dir->AppendNative("OfflineCache"_ns); if (NS_FAILED(rv)) return; mCacheDirectory = dir; diff --git a/netwerk/cache2/AppCacheStorage.cpp b/netwerk/cache2/AppCacheStorage.cpp index cf8bb36c794a..109288023258 100644 --- a/netwerk/cache2/AppCacheStorage.cpp +++ b/netwerk/cache2/AppCacheStorage.cpp @@ -70,7 +70,7 @@ NS_IMETHODIMP AppCacheStorage::AsyncOpenURI( // there is just a single session for an appcache version (identified // by the client id). if (LoadInfo()->IsAnonymous()) { - cacheKey = NS_LITERAL_CSTRING("anon&") + cacheKey; + cacheKey = "anon&"_ns + cacheKey; } nsAutoCString scheme; diff --git a/netwerk/cache2/CacheFileContextEvictor.cpp b/netwerk/cache2/CacheFileContextEvictor.cpp index 84027296a18c..5b5a193289a6 100644 --- a/netwerk/cache2/CacheFileContextEvictor.cpp +++ b/netwerk/cache2/CacheFileContextEvictor.cpp @@ -51,7 +51,7 @@ nsresult CacheFileContextEvictor::Init(nsIFile* aCacheDirectory) { return rv; } - rv = mEntriesDir->AppendNative(NS_LITERAL_CSTRING(ENTRIES_DIR)); + rv = mEntriesDir->AppendNative(nsLiteralCString(ENTRIES_DIR)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -368,7 +368,7 @@ nsresult CacheFileContextEvictor::LoadEvictInfoFromDisk() { continue; } - if (!StringBeginsWith(leaf, NS_LITERAL_CSTRING(CONTEXT_EVICTION_PREFIX))) { + if (!StringBeginsWith(leaf, nsLiteralCString(CONTEXT_EVICTION_PREFIX))) { continue; } @@ -403,7 +403,7 @@ nsresult CacheFileContextEvictor::LoadEvictInfoFromDisk() { } nsCOMPtr info; - if (!NS_LITERAL_CSTRING("*").Equals(decoded)) { + if (!"*"_ns.Equals(decoded)) { // "*" is indication of 'delete all', info left null will pass // to CacheFileContextEvictor::AddContext and clear all the cache data. info = CacheFileUtils::ParseKey(decoded); diff --git a/netwerk/cache2/CacheFileIOManager.cpp b/netwerk/cache2/CacheFileIOManager.cpp index 90fc8eaccb42..9281b18ba78e 100644 --- a/netwerk/cache2/CacheFileIOManager.cpp +++ b/netwerk/cache2/CacheFileIOManager.cpp @@ -1318,7 +1318,7 @@ nsresult CacheFileIOManager::OnProfile() { } if (directory) { - rv = directory->Append(NS_LITERAL_STRING("cache2")); + rv = directory->Append(u"cache2"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -1327,7 +1327,7 @@ nsresult CacheFileIOManager::OnProfile() { #if defined(MOZ_WIDGET_ANDROID) if (profilelessDirectory) { - rv = profilelessDirectory->Append(NS_LITERAL_STRING("cache2")); + rv = profilelessDirectory->Append(u"cache2"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -2980,7 +2980,7 @@ nsresult CacheFileIOManager::EvictAllInternal() { return rv; } - rv = file->AppendNative(NS_LITERAL_CSTRING(ENTRIES_DIR)); + rv = file->AppendNative(nsLiteralCString(ENTRIES_DIR)); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -3470,7 +3470,7 @@ nsresult CacheFileIOManager::FindTrashDirToRemove() { continue; } - if (!StringBeginsWith(leafName, NS_LITERAL_CSTRING(TRASH_DIR))) { + if (!StringBeginsWith(leafName, nsLiteralCString(TRASH_DIR))) { continue; } @@ -3636,7 +3636,7 @@ nsresult CacheFileIOManager::GetFile(const SHA1Sum::Hash* aHash, rv = mCacheDirectory->Clone(getter_AddRefs(file)); NS_ENSURE_SUCCESS(rv, rv); - rv = file->AppendNative(NS_LITERAL_CSTRING(ENTRIES_DIR)); + rv = file->AppendNative(nsLiteralCString(ENTRIES_DIR)); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString leafName; @@ -3669,10 +3669,10 @@ nsresult CacheFileIOManager::GetDoomedFile(nsIFile** _retval) { rv = mCacheDirectory->Clone(getter_AddRefs(file)); NS_ENSURE_SUCCESS(rv, rv); - rv = file->AppendNative(NS_LITERAL_CSTRING(DOOMED_DIR)); + rv = file->AppendNative(nsLiteralCString(DOOMED_DIR)); NS_ENSURE_SUCCESS(rv, rv); - rv = file->AppendNative(NS_LITERAL_CSTRING("dummyleaf")); + rv = file->AppendNative("dummyleaf"_ns); NS_ENSURE_SUCCESS(rv, rv); const int32_t kMaxTries = 64; diff --git a/netwerk/cache2/CacheFileUtils.cpp b/netwerk/cache2/CacheFileUtils.cpp index 90dc1170d739..f4aa63e1006a 100644 --- a/netwerk/cache2/CacheFileUtils.cpp +++ b/netwerk/cache2/CacheFileUtils.cpp @@ -223,8 +223,7 @@ void AppendTagWithValue(nsACString& aTarget, char const aTag, aTarget.Append(aValue); } else { nsAutoCString escapedValue(aValue); - escapedValue.ReplaceSubstring(NS_LITERAL_CSTRING(","), - NS_LITERAL_CSTRING(",,")); + escapedValue.ReplaceSubstring(","_ns, ",,"_ns); aTarget.Append(escapedValue); } } diff --git a/netwerk/cache2/CacheIndex.cpp b/netwerk/cache2/CacheIndex.cpp index f19d5dd9dbe4..a77bcfc23d92 100644 --- a/netwerk/cache2/CacheIndex.cpp +++ b/netwerk/cache2/CacheIndex.cpp @@ -1102,7 +1102,7 @@ nsresult CacheIndex::RemoveAll() { } else { // We don't have a handle to index file, so get the file here, but delete // it outside the lock. Ignore the result since this is not fatal. - index->GetFile(NS_LITERAL_CSTRING(INDEX_NAME), getter_AddRefs(file)); + index->GetFile(nsLiteralCString(INDEX_NAME), getter_AddRefs(file)); } if (index->mJournalHandle) { @@ -1691,7 +1691,7 @@ void CacheIndex::WriteIndexToDisk() { mIndexFileOpener = new FileOpenHelper(this); rv = CacheFileIOManager::OpenFile( - NS_LITERAL_CSTRING(TEMP_INDEX_NAME), + nsLiteralCString(TEMP_INDEX_NAME), CacheFileIOManager::SPECIAL_FILE | CacheFileIOManager::CREATE, mIndexFileOpener); if (NS_FAILED(rv)) { @@ -1907,14 +1907,14 @@ void CacheIndex::RemoveFile(const nsACString& aName) { void CacheIndex::RemoveAllIndexFiles() { LOG(("CacheIndex::RemoveAllIndexFiles()")); - RemoveFile(NS_LITERAL_CSTRING(INDEX_NAME)); + RemoveFile(nsLiteralCString(INDEX_NAME)); RemoveJournalAndTempFile(); } void CacheIndex::RemoveJournalAndTempFile() { LOG(("CacheIndex::RemoveJournalAndTempFile()")); - RemoveFile(NS_LITERAL_CSTRING(TEMP_INDEX_NAME)); - RemoveFile(NS_LITERAL_CSTRING(JOURNAL_NAME)); + RemoveFile(nsLiteralCString(TEMP_INDEX_NAME)); + RemoveFile(nsLiteralCString(JOURNAL_NAME)); } class WriteLogHelper { @@ -2005,14 +2005,14 @@ nsresult CacheIndex::WriteLogToDisk() { return NS_ERROR_FAILURE; } - RemoveFile(NS_LITERAL_CSTRING(TEMP_INDEX_NAME)); + RemoveFile(nsLiteralCString(TEMP_INDEX_NAME)); nsCOMPtr indexFile; - rv = GetFile(NS_LITERAL_CSTRING(INDEX_NAME), getter_AddRefs(indexFile)); + rv = GetFile(nsLiteralCString(INDEX_NAME), getter_AddRefs(indexFile)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr logFile; - rv = GetFile(NS_LITERAL_CSTRING(JOURNAL_NAME), getter_AddRefs(logFile)); + rv = GetFile(nsLiteralCString(JOURNAL_NAME), getter_AddRefs(logFile)); NS_ENSURE_SUCCESS(rv, rv); mIndexStats.Log(); @@ -2071,7 +2071,7 @@ void CacheIndex::ReadIndexFromDisk() { mIndexFileOpener = new FileOpenHelper(this); rv = CacheFileIOManager::OpenFile( - NS_LITERAL_CSTRING(INDEX_NAME), + nsLiteralCString(INDEX_NAME), CacheFileIOManager::SPECIAL_FILE | CacheFileIOManager::OPEN, mIndexFileOpener); if (NS_FAILED(rv)) { @@ -2085,7 +2085,7 @@ void CacheIndex::ReadIndexFromDisk() { mJournalFileOpener = new FileOpenHelper(this); rv = CacheFileIOManager::OpenFile( - NS_LITERAL_CSTRING(JOURNAL_NAME), + nsLiteralCString(JOURNAL_NAME), CacheFileIOManager::SPECIAL_FILE | CacheFileIOManager::OPEN, mJournalFileOpener); if (NS_FAILED(rv)) { @@ -2098,7 +2098,7 @@ void CacheIndex::ReadIndexFromDisk() { mTmpFileOpener = new FileOpenHelper(this); rv = CacheFileIOManager::OpenFile( - NS_LITERAL_CSTRING(TEMP_INDEX_NAME), + nsLiteralCString(TEMP_INDEX_NAME), CacheFileIOManager::SPECIAL_FILE | CacheFileIOManager::OPEN, mTmpFileOpener); if (NS_FAILED(rv)) { @@ -2482,8 +2482,8 @@ void CacheIndex::FinishRead(bool aSucceeded) { MOZ_ASSERT(!mRWPending || (!aSucceeded && (mShuttingDown || mRemovingAll))); if (mState == SHUTDOWN) { - RemoveFile(NS_LITERAL_CSTRING(TEMP_INDEX_NAME)); - RemoveFile(NS_LITERAL_CSTRING(JOURNAL_NAME)); + RemoveFile(nsLiteralCString(TEMP_INDEX_NAME)); + RemoveFile(nsLiteralCString(JOURNAL_NAME)); } else { if (mIndexHandle && !mIndexOnDiskIsValid) { CacheFileIOManager::DoomFile(mIndexHandle, nullptr); @@ -2621,7 +2621,7 @@ nsresult CacheIndex::SetupDirectoryEnumerator() { rv = mCacheDirectory->Clone(getter_AddRefs(file)); NS_ENSURE_SUCCESS(rv, rv); - rv = file->AppendNative(NS_LITERAL_CSTRING(ENTRIES_DIR)); + rv = file->AppendNative(nsLiteralCString(ENTRIES_DIR)); NS_ENSURE_SUCCESS(rv, rv); bool exists; @@ -3564,7 +3564,7 @@ void CacheIndex::OnFileOpenedInternal(FileOpenHelper* aOpener, // Rename journal to make sure we update index on next start in case // firefox crashes rv = CacheFileIOManager::RenameFile( - mJournalHandle, NS_LITERAL_CSTRING(TEMP_INDEX_NAME), this); + mJournalHandle, nsLiteralCString(TEMP_INDEX_NAME), this); if (NS_FAILED(rv)) { LOG( ("CacheIndex::OnFileOpenedInternal() - CacheFileIOManager::" @@ -3616,7 +3616,7 @@ nsresult CacheIndex::OnDataWritten(CacheFileHandle* aHandle, const char* aBuf, } else { if (mSkipEntries == mProcessEntries) { rv = CacheFileIOManager::RenameFile( - mIndexHandle, NS_LITERAL_CSTRING(INDEX_NAME), this); + mIndexHandle, nsLiteralCString(INDEX_NAME), this); if (NS_FAILED(rv)) { LOG( ("CacheIndex::OnDataWritten() - CacheFileIOManager::" @@ -3904,10 +3904,8 @@ void CacheIndex::UpdateTotalBytesWritten(uint32_t aBytesWritten) { void CacheIndex::DoTelemetryReport() { static const nsLiteralCString contentTypeNames[nsICacheEntry::CONTENT_TYPE_LAST] = { - NS_LITERAL_CSTRING("UNKNOWN"), NS_LITERAL_CSTRING("OTHER"), - NS_LITERAL_CSTRING("JAVASCRIPT"), NS_LITERAL_CSTRING("IMAGE"), - NS_LITERAL_CSTRING("MEDIA"), NS_LITERAL_CSTRING("STYLESHEET"), - NS_LITERAL_CSTRING("WASM")}; + "UNKNOWN"_ns, "OTHER"_ns, "JAVASCRIPT"_ns, "IMAGE"_ns, + "MEDIA"_ns, "STYLESHEET"_ns, "WASM"_ns}; for (uint32_t i = 0; i < nsICacheEntry::CONTENT_TYPE_LAST; ++i) { if (mIndexStats.Size() > 0) { @@ -3927,9 +3925,9 @@ void CacheIndex::DoTelemetryReport() { nsCString probeKey; if (CacheObserver::SmartCacheSizeEnabled()) { - probeKey = NS_LITERAL_CSTRING("SMARTSIZE"); + probeKey = "SMARTSIZE"_ns; } else { - probeKey = NS_LITERAL_CSTRING("USERDEFINEDSIZE"); + probeKey = "USERDEFINEDSIZE"_ns; } Telemetry::Accumulate(Telemetry::NETWORK_CACHE_ENTRY_COUNT, probeKey, mIndexStats.Count()); diff --git a/netwerk/cache2/CacheStorageService.cpp b/netwerk/cache2/CacheStorageService.cpp index be17317bfe85..fa9c3a9d354e 100644 --- a/netwerk/cache2/CacheStorageService.cpp +++ b/netwerk/cache2/CacheStorageService.cpp @@ -2295,7 +2295,7 @@ CacheStorageService::CollectReports(nsIHandleReportCallback* aHandleReport, table->Type() == CacheEntryTable::MEMORY_ONLY ? "memory" : "disk", aAnonymize ? "" : iter1.Key().BeginReading()), nsIMemoryReporter::KIND_HEAP, nsIMemoryReporter::UNITS_BYTES, size, - NS_LITERAL_CSTRING("Memory used by the cache storage."), aData); + "Memory used by the cache storage."_ns, aData); } } diff --git a/netwerk/cache2/OldWrappers.cpp b/netwerk/cache2/OldWrappers.cpp index 449ee3496871..e6147ad95007 100644 --- a/netwerk/cache2/OldWrappers.cpp +++ b/netwerk/cache2/OldWrappers.cpp @@ -195,7 +195,7 @@ NS_IMETHODIMP _OldVisitCallbackWrapper::VisitEntry(const char* deviceID, if (NS_FAILED(rv)) return NS_OK; if (mLoadInfo->IsPrivate() != - StringBeginsWith(clientId, NS_LITERAL_CSTRING("HTTP-memory-only-PB"))) { + StringBeginsWith(clientId, "HTTP-memory-only-PB"_ns)) { return NS_OK; } @@ -203,7 +203,7 @@ NS_IMETHODIMP _OldVisitCallbackWrapper::VisitEntry(const char* deviceID, rv = entryInfo->GetKey(cacheKey); if (NS_FAILED(rv)) return NS_OK; - if (StringBeginsWith(cacheKey, NS_LITERAL_CSTRING("anon&"))) { + if (StringBeginsWith(cacheKey, "anon&"_ns)) { if (!mLoadInfo->IsAnonymous()) return NS_OK; cacheKey = Substring(cacheKey, 5, cacheKey.Length()); @@ -211,7 +211,7 @@ NS_IMETHODIMP _OldVisitCallbackWrapper::VisitEntry(const char* deviceID, return NS_OK; } - if (StringBeginsWith(cacheKey, NS_LITERAL_CSTRING("id="))) { + if (StringBeginsWith(cacheKey, "id="_ns)) { int32_t uriSpecEnd = cacheKey.Find("&uri="); if (uriSpecEnd == kNotFound) // Corrupted, ignore return NS_OK; @@ -220,7 +220,7 @@ NS_IMETHODIMP _OldVisitCallbackWrapper::VisitEntry(const char* deviceID, cacheKey = Substring(cacheKey, uriSpecEnd + 1, cacheKey.Length()); } - if (StringBeginsWith(cacheKey, NS_LITERAL_CSTRING("uri="))) { + if (StringBeginsWith(cacheKey, "uri="_ns)) { cacheKey = Substring(cacheKey, 4, cacheKey.Length()); } @@ -913,8 +913,8 @@ NS_IMETHODIMP _OldStorage::AsyncEvictStorage( } else { // Oh, I'll be so happy when session names are gone... nsCOMPtr session; - rv = GetCacheSession(NS_LITERAL_CSTRING("http"), mWriteToDisk, mLoadInfo, - mAppCache, getter_AddRefs(session)); + rv = GetCacheSession("http"_ns, mWriteToDisk, mLoadInfo, mAppCache, + getter_AddRefs(session)); NS_ENSURE_SUCCESS(rv, rv); rv = session->EvictEntries(); diff --git a/netwerk/cookie/CookieCommons.cpp b/netwerk/cookie/CookieCommons.cpp index de02acf1fb49..677c25ebfbff 100644 --- a/netwerk/cookie/CookieCommons.cpp +++ b/netwerk/cookie/CookieCommons.cpp @@ -20,8 +20,7 @@ #include "nsIRedirectHistoryEntry.h" #include "nsScriptSecurityManager.h" -constexpr auto CONSOLE_SCHEMEFUL_CATEGORY = - NS_LITERAL_CSTRING("cookieSchemeful"); +constexpr auto CONSOLE_SCHEMEFUL_CATEGORY = "cookieSchemeful"_ns; namespace mozilla { @@ -586,7 +585,7 @@ bool CookieCommons::MaybeCompareSchemeWithLogging( if (!StaticPrefs::network_cookie_sameSite_schemeful()) { CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_SCHEMEFUL_CATEGORY, - NS_LITERAL_CSTRING("CookieSchemefulRejectForBeta"), + "CookieSchemefulRejectForBeta"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookie->Name()), NS_ConvertUTF8toUTF16(uri)}); return true; @@ -594,7 +593,7 @@ bool CookieCommons::MaybeCompareSchemeWithLogging( CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_SCHEMEFUL_CATEGORY, - NS_LITERAL_CSTRING("CookieSchemefulReject"), + "CookieSchemefulReject"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookie->Name()), NS_ConvertUTF8toUTF16(uri)}); return false; diff --git a/netwerk/cookie/CookieJarSettings.cpp b/netwerk/cookie/CookieJarSettings.cpp index 12a451190052..a98bc3045beb 100644 --- a/netwerk/cookie/CookieJarSettings.cpp +++ b/netwerk/cookie/CookieJarSettings.cpp @@ -258,8 +258,8 @@ CookieJarSettings::CookiePermission(nsIPrincipal* aPrincipal, } else // Note the tricky `else` which controls the call below. #endif - rv = pm->TestPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("cookie"), aCookiePermission); + rv = pm->TestPermissionFromPrincipal(aPrincipal, "cookie"_ns, + aCookiePermission); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -267,8 +267,8 @@ CookieJarSettings::CookiePermission(nsIPrincipal* aPrincipal, // Let's store the permission, also if the result is UNKNOWN in order to avoid // race conditions. - nsCOMPtr permission = Permission::Create( - aPrincipal, NS_LITERAL_CSTRING("cookie"), *aCookiePermission, 0, 0, 0); + nsCOMPtr permission = + Permission::Create(aPrincipal, "cookie"_ns, *aCookiePermission, 0, 0, 0); if (permission) { mCookiePermissions.AppendElement(permission); } @@ -327,9 +327,8 @@ void CookieJarSettings::Serialize(CookieJarSettingsArgs& aData) { nsCOMPtr principal = principalOrErr.unwrap(); - nsCOMPtr permission = - Permission::Create(principal, NS_LITERAL_CSTRING("cookie"), - data.cookiePermission(), 0, 0, 0); + nsCOMPtr permission = Permission::Create( + principal, "cookie"_ns, data.cookiePermission(), 0, 0, 0); if (NS_WARN_IF(!permission)) { continue; } @@ -400,9 +399,8 @@ void CookieJarSettings::Merge(const CookieJarSettingsArgs& aData) { } nsCOMPtr principal = principalOrErr.unwrap(); - nsCOMPtr permission = - Permission::Create(principal, NS_LITERAL_CSTRING("cookie"), - data.cookiePermission(), 0, 0, 0); + nsCOMPtr permission = Permission::Create( + principal, "cookie"_ns, data.cookiePermission(), 0, 0, 0); if (NS_WARN_IF(!permission)) { continue; } diff --git a/netwerk/cookie/CookiePersistentStorage.cpp b/netwerk/cookie/CookiePersistentStorage.cpp index 153ea434353a..5153f6f5450c 100644 --- a/netwerk/cookie/CookiePersistentStorage.cpp +++ b/netwerk/cookie/CookiePersistentStorage.cpp @@ -66,55 +66,43 @@ void BindCookieParameters(mozIStorageBindingParamsArray* aParamsArray, nsAutoCString suffix; aKey.mOriginAttributes.CreateSuffix(suffix); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), - suffix); + rv = params->BindUTF8StringByName("originAttributes"_ns, suffix); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = - params->BindUTF8StringByName(NS_LITERAL_CSTRING("name"), aCookie->Name()); + rv = params->BindUTF8StringByName("name"_ns, aCookie->Name()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), - aCookie->Value()); + rv = params->BindUTF8StringByName("value"_ns, aCookie->Value()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = - params->BindUTF8StringByName(NS_LITERAL_CSTRING("host"), aCookie->Host()); + rv = params->BindUTF8StringByName("host"_ns, aCookie->Host()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = - params->BindUTF8StringByName(NS_LITERAL_CSTRING("path"), aCookie->Path()); + rv = params->BindUTF8StringByName("path"_ns, aCookie->Path()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt64ByName(NS_LITERAL_CSTRING("expiry"), aCookie->Expiry()); + rv = params->BindInt64ByName("expiry"_ns, aCookie->Expiry()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt64ByName(NS_LITERAL_CSTRING("lastAccessed"), - aCookie->LastAccessed()); + rv = params->BindInt64ByName("lastAccessed"_ns, aCookie->LastAccessed()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt64ByName(NS_LITERAL_CSTRING("creationTime"), - aCookie->CreationTime()); + rv = params->BindInt64ByName("creationTime"_ns, aCookie->CreationTime()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt32ByName(NS_LITERAL_CSTRING("isSecure"), - aCookie->IsSecure()); + rv = params->BindInt32ByName("isSecure"_ns, aCookie->IsSecure()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt32ByName(NS_LITERAL_CSTRING("isHttpOnly"), - aCookie->IsHttpOnly()); + rv = params->BindInt32ByName("isHttpOnly"_ns, aCookie->IsHttpOnly()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt32ByName(NS_LITERAL_CSTRING("sameSite"), - aCookie->SameSite()); + rv = params->BindInt32ByName("sameSite"_ns, aCookie->SameSite()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt32ByName(NS_LITERAL_CSTRING("rawSameSite"), - aCookie->RawSameSite()); + rv = params->BindInt32ByName("rawSameSite"_ns, aCookie->RawSameSite()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindInt32ByName(NS_LITERAL_CSTRING("schemeMap"), - aCookie->SchemeMap()); + rv = params->BindInt32ByName("schemeMap"_ns, aCookie->SchemeMap()); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Bind the params to the array. @@ -389,9 +377,8 @@ void CookiePersistentStorage::NotifyChangedInternal(nsISupports* aSubject, // cookies in session restore component. // Filter out notifications for individual non-session cookies. - if (NS_LITERAL_STRING("changed").Equals(aData) || - NS_LITERAL_STRING("deleted").Equals(aData) || - NS_LITERAL_STRING("added").Equals(aData)) { + if (u"changed"_ns.Equals(aData) || u"deleted"_ns.Equals(aData) || + u"added"_ns.Equals(aData)) { nsCOMPtr xpcCookie = do_QueryInterface(aSubject); MOZ_ASSERT(xpcCookie); auto cookie = static_cast(xpcCookie.get()); @@ -410,8 +397,8 @@ void CookiePersistentStorage::RemoveAllInternal() { // clear the cookie file if (mDBConn) { nsCOMPtr stmt; - nsresult rv = mDBConn->CreateAsyncStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cookies"), getter_AddRefs(stmt)); + nsresult rv = mDBConn->CreateAsyncStatement("DELETE FROM moz_cookies"_ns, + getter_AddRefs(stmt)); if (NS_SUCCEEDED(rv)) { nsCOMPtr handle; rv = stmt->ExecuteAsync(mRemoveListener, getter_AddRefs(handle)); @@ -512,22 +499,19 @@ void CookiePersistentStorage::PrepareCookieRemoval( nsCOMPtr params; aParamsArray->NewBindingParams(getter_AddRefs(params)); - DebugOnly rv = params->BindUTF8StringByName( - NS_LITERAL_CSTRING("name"), aIter.Cookie()->Name()); + DebugOnly rv = + params->BindUTF8StringByName("name"_ns, aIter.Cookie()->Name()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("host"), - aIter.Cookie()->Host()); + rv = params->BindUTF8StringByName("host"_ns, aIter.Cookie()->Host()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("path"), - aIter.Cookie()->Path()); + rv = params->BindUTF8StringByName("path"_ns, aIter.Cookie()->Path()); MOZ_ASSERT(NS_SUCCEEDED(rv)); nsAutoCString suffix; aIter.Cookie()->OriginAttributesRef().CreateSuffix(suffix); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), - suffix); + rv = params->BindUTF8StringByName("originAttributes"_ns, suffix); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = aParamsArray->AddParams(params); @@ -671,26 +655,22 @@ void CookiePersistentStorage::UpdateCookieInList( aParamsArray->NewBindingParams(getter_AddRefs(params)); // Bind our parameters. - DebugOnly rv = params->BindInt64ByName( - NS_LITERAL_CSTRING("lastAccessed"), aLastAccessed); + DebugOnly rv = + params->BindInt64ByName("lastAccessed"_ns, aLastAccessed); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("name"), - aCookie->Name()); + rv = params->BindUTF8StringByName("name"_ns, aCookie->Name()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("host"), - aCookie->Host()); + rv = params->BindUTF8StringByName("host"_ns, aCookie->Host()); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("path"), - aCookie->Path()); + rv = params->BindUTF8StringByName("path"_ns, aCookie->Path()); MOZ_ASSERT(NS_SUCCEEDED(rv)); nsAutoCString suffix; aCookie->OriginAttributesRef().CreateSuffix(suffix); - rv = params->BindUTF8StringByName(NS_LITERAL_CSTRING("originAttributes"), - suffix); + rv = params->BindUTF8StringByName("originAttributes"_ns, suffix); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Add our bound parameters to the array. @@ -736,7 +716,7 @@ void CookiePersistentStorage::Activate() { return; } - mCookieFile->AppendNative(NS_LITERAL_CSTRING(COOKIES_FILE)); + mCookieFile->AppendNative(nsLiteralCString(COOKIES_FILE)); NS_ENSURE_SUCCESS_VOID(NS_NewNamedThread("Cookie", getter_AddRefs(mThread))); @@ -816,7 +796,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( nsCOMPtr backupFile; mCookieFile->Clone(getter_AddRefs(backupFile)); rv = backupFile->MoveToNative(nullptr, - NS_LITERAL_CSTRING(COOKIES_FILE ".bak")); + nsLiteralCString(COOKIES_FILE ".bak")); NS_ENSURE_SUCCESS(rv, RESULT_FAILURE); } @@ -837,7 +817,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( auto guard = MakeScopeExit([&] { mSyncConn = nullptr; }); bool tableExists = false; - mSyncConn->TableExists(NS_LITERAL_CSTRING("moz_cookies"), &tableExists); + mSyncConn->TableExists("moz_cookies"_ns, &tableExists); if (!tableExists) { rv = CreateTable(); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -860,7 +840,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( // might one day see it and fix it. case 1: { // Add the lastAccessed column to the table. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD lastAccessed INTEGER")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); } @@ -870,7 +850,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( case 2: { // Add the baseDomain column and index to the table. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_cookies ADD baseDomain TEXT")); + "ALTER TABLE moz_cookies ADD baseDomain TEXT"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Compute the baseDomains for the table. This must be done eagerly @@ -879,15 +859,14 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( const int64_t SCHEMA2_IDX_ID = 0; const int64_t SCHEMA2_IDX_HOST = 1; nsCOMPtr select; - rv = mSyncConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT id, host FROM moz_cookies"), - getter_AddRefs(select)); + rv = mSyncConn->CreateStatement("SELECT id, host FROM moz_cookies"_ns, + getter_AddRefs(select)); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); nsCOMPtr update; rv = mSyncConn->CreateStatement( - NS_LITERAL_CSTRING("UPDATE moz_cookies SET baseDomain = " - ":baseDomain WHERE id = :id"), + nsLiteralCString("UPDATE moz_cookies SET baseDomain = " + ":baseDomain WHERE id = :id"), getter_AddRefs(update)); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -911,10 +890,9 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( mozStorageStatementScoper scoper(update); - rv = update->BindUTF8StringByName(NS_LITERAL_CSTRING("baseDomain"), - baseDomain); + rv = update->BindUTF8StringByName("baseDomain"_ns, baseDomain); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = update->BindInt64ByName(NS_LITERAL_CSTRING("id"), id); + rv = update->BindInt64ByName("id"_ns, id); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = update->ExecuteStep(&hasResult); @@ -922,7 +900,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( } // Create an index on baseDomain. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); } @@ -947,7 +925,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( const int64_t SCHEMA3_IDX_PATH = 3; nsCOMPtr select; rv = mSyncConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id, name, host, path FROM moz_cookies " "ORDER BY name ASC, host ASC, path ASC, expiry ASC"), getter_AddRefs(select)); @@ -955,7 +933,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( nsCOMPtr deleteExpired; rv = mSyncConn->CreateStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cookies WHERE id = :id"), + "DELETE FROM moz_cookies WHERE id = :id"_ns, getter_AddRefs(deleteExpired)); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -995,8 +973,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( if (name1 == name2 && host1 == host2 && path1 == path2) { mozStorageStatementScoper scoper(deleteExpired); - rv = - deleteExpired->BindInt64ByName(NS_LITERAL_CSTRING("id"), id1); + rv = deleteExpired->BindInt64ByName("id"_ns, id1); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = deleteExpired->ExecuteStep(&hasResult); @@ -1012,20 +989,20 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( } // Add the creationTime column to the table. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD creationTime INTEGER")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Copy the id of each row into the new creationTime column. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_cookies SET creationTime = " - "(SELECT id WHERE id = moz_cookies.id)")); + nsLiteralCString("UPDATE moz_cookies SET creationTime = " + "(SELECT id WHERE id = moz_cookies.id)")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Create a unique index on (name, host, path) to allow fast lookup. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE UNIQUE INDEX moz_uniqueid " - "ON moz_cookies (name, host, path)")); + nsLiteralCString("CREATE UNIQUE INDEX moz_uniqueid " + "ON moz_cookies (name, host, path)")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); } // Fall through to the next upgrade. @@ -1044,13 +1021,12 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( // the only namespace used by a non-Firefox-OS implementation. // Rename existing table - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies RENAME TO moz_cookies_old")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop existing index (CreateTable will create new one for new table) - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX moz_basedomain")); + rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Create new table (with new fields and new unique constraint) @@ -1058,7 +1034,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Copy data from old table, using appId/inBrowser=0 for existing rows - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO moz_cookies " "(baseDomain, appId, inBrowserElement, name, value, host, path, " "expiry," @@ -1069,8 +1045,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop old table - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_cookies_old")); + rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1095,13 +1070,12 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( // inBrowserElement to originAttributes in the meantime. // Rename existing table. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies RENAME TO moz_cookies_old")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop existing index (CreateTable will create new one for new table). - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX moz_basedomain")); + rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Create new table with new fields and new unique constraint. @@ -1121,7 +1095,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( convertToOriginAttrs); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO moz_cookies " "(baseDomain, originAttributes, name, value, host, path, expiry," " lastAccessed, creationTime, isSecure, isHttpOnly) " @@ -1136,8 +1110,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop old table - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_cookies_old")); + rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1154,11 +1127,11 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( // This version simply restores appId and inBrowserElement columns in // order to fix downgrading issue even though these two columns are no // longer used in the latest schema. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD appId INTEGER DEFAULT 0;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD inBrowserElement INTEGER DEFAULT 0;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -1182,7 +1155,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( rv = mSyncConn->CreateFunction(setInBrowserName, 1, setInBrowser); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_cookies SET appId = SET_APP_ID(originAttributes), " "inBrowserElement = SET_IN_BROWSER(originAttributes);")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -1206,78 +1179,76 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( // https://www.sqlite.org/lang_altertable.html. // Drop existing index - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX moz_basedomain")); + rv = mSyncConn->ExecuteSimpleSQL("DROP INDEX moz_basedomain"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Create a new_moz_cookies table without the appId field. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE new_moz_cookies(" - "id INTEGER PRIMARY KEY, " - "baseDomain TEXT, " - "originAttributes TEXT NOT NULL DEFAULT '', " - "name TEXT, " - "value TEXT, " - "host TEXT, " - "path TEXT, " - "expiry INTEGER, " - "lastAccessed INTEGER, " - "creationTime INTEGER, " - "isSecure INTEGER, " - "isHttpOnly INTEGER, " - "inBrowserElement INTEGER DEFAULT 0, " - "CONSTRAINT moz_uniqueid UNIQUE (name, host, " - "path, originAttributes)" - ")")); + nsLiteralCString("CREATE TABLE new_moz_cookies(" + "id INTEGER PRIMARY KEY, " + "baseDomain TEXT, " + "originAttributes TEXT NOT NULL DEFAULT '', " + "name TEXT, " + "value TEXT, " + "host TEXT, " + "path TEXT, " + "expiry INTEGER, " + "lastAccessed INTEGER, " + "creationTime INTEGER, " + "isSecure INTEGER, " + "isHttpOnly INTEGER, " + "inBrowserElement INTEGER DEFAULT 0, " + "CONSTRAINT moz_uniqueid UNIQUE (name, host, " + "path, originAttributes)" + ")")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Move the data over. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO new_moz_cookies (" - "id, " - "baseDomain, " - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "inBrowserElement " - ") SELECT " - "id, " - "baseDomain, " - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "inBrowserElement " - "FROM moz_cookies;")); + nsLiteralCString("INSERT INTO new_moz_cookies (" + "id, " + "baseDomain, " + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "inBrowserElement " + ") SELECT " + "id, " + "baseDomain, " + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "inBrowserElement " + "FROM moz_cookies;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop the old table - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_cookies;")); + rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies;"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Rename new_moz_cookies to moz_cookies. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE new_moz_cookies RENAME TO moz_cookies;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Recreate our index. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE INDEX moz_basedomain ON moz_cookies " - "(baseDomain, originAttributes)")); + nsLiteralCString("CREATE INDEX moz_basedomain ON moz_cookies " + "(baseDomain, originAttributes)")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1288,7 +1259,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( case 8: { // Add the sameSite column to the table. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_cookies ADD sameSite INTEGER")); + "ALTER TABLE moz_cookies ADD sameSite INTEGER"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1298,13 +1269,13 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( case 9: { // Add the rawSameSite column to the table. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD rawSameSite INTEGER")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Copy the current sameSite value into rawSameSite. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "UPDATE moz_cookies SET rawSameSite = sameSite")); + rv = mSyncConn->ExecuteSimpleSQL( + "UPDATE moz_cookies SET rawSameSite = sameSite"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1314,77 +1285,76 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( case 10: { // Rename existing table - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies RENAME TO moz_cookies_old")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Create a new moz_cookies table without the baseDomain field. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_cookies(" - "id INTEGER PRIMARY KEY, " - "originAttributes TEXT NOT NULL DEFAULT '', " - "name TEXT, " - "value TEXT, " - "host TEXT, " - "path TEXT, " - "expiry INTEGER, " - "lastAccessed INTEGER, " - "creationTime INTEGER, " - "isSecure INTEGER, " - "isHttpOnly INTEGER, " - "inBrowserElement INTEGER DEFAULT 0, " - "sameSite INTEGER DEFAULT 0, " - "rawSameSite INTEGER DEFAULT 0, " - "CONSTRAINT moz_uniqueid UNIQUE (name, host, " - "path, originAttributes)" - ")")); + nsLiteralCString("CREATE TABLE moz_cookies(" + "id INTEGER PRIMARY KEY, " + "originAttributes TEXT NOT NULL DEFAULT '', " + "name TEXT, " + "value TEXT, " + "host TEXT, " + "path TEXT, " + "expiry INTEGER, " + "lastAccessed INTEGER, " + "creationTime INTEGER, " + "isSecure INTEGER, " + "isHttpOnly INTEGER, " + "inBrowserElement INTEGER DEFAULT 0, " + "sameSite INTEGER DEFAULT 0, " + "rawSameSite INTEGER DEFAULT 0, " + "CONSTRAINT moz_uniqueid UNIQUE (name, host, " + "path, originAttributes)" + ")")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Move the data over. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO moz_cookies (" - "id, " - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "inBrowserElement, " - "sameSite, " - "rawSameSite " - ") SELECT " - "id, " - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "inBrowserElement, " - "sameSite, " - "rawSameSite " - "FROM moz_cookies_old " - "WHERE baseDomain NOTNULL;")); + nsLiteralCString("INSERT INTO moz_cookies (" + "id, " + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "inBrowserElement, " + "sameSite, " + "rawSameSite " + ") SELECT " + "id, " + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "inBrowserElement, " + "sameSite, " + "rawSameSite " + "FROM moz_cookies_old " + "WHERE baseDomain NOTNULL;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop the old table - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_cookies_old;")); + rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies_old;"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); // Drop the moz_basedomain index from the database (if it hasn't been // removed already by removing the table). rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX IF EXISTS moz_basedomain;")); + "DROP INDEX IF EXISTS moz_basedomain;"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); COOKIE_LOGSTRING(LogLevel::Debug, @@ -1394,7 +1364,7 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( case 11: { // Add the schemeMap column to the table. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_cookies ADD schemeMap INTEGER DEFAULT 0;")); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -1433,30 +1403,29 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::TryInitDB( default: { // check if all the expected columns exist nsCOMPtr stmt; - rv = mSyncConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "id, " - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "sameSite, " - "rawSameSite, " - "schemeMap " - "FROM moz_cookies"), + rv = mSyncConn->CreateStatement(nsLiteralCString("SELECT " + "id, " + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "sameSite, " + "rawSameSite, " + "schemeMap " + "FROM moz_cookies"), getter_AddRefs(stmt)); if (NS_SUCCEEDED(rv)) { break; } // our columns aren't there - drop the table! - rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE moz_cookies")); + rv = mSyncConn->ExecuteSimpleSQL("DROP TABLE moz_cookies"_ns); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); rv = CreateTable(); @@ -1587,7 +1556,7 @@ void CookiePersistentStorage::HandleDBClosed() { nsCOMPtr backupFile; mCookieFile->Clone(getter_AddRefs(backupFile)); nsresult rv = backupFile->MoveToNative( - nullptr, NS_LITERAL_CSTRING(COOKIES_FILE ".bak-rebuild")); + nullptr, nsLiteralCString(COOKIES_FILE ".bak-rebuild")); COOKIE_LOGSTRING(LogLevel::Warning, ("HandleDBClosed(): CookieStorage %p encountered error " @@ -1608,23 +1577,22 @@ CookiePersistentStorage::OpenDBResult CookiePersistentStorage::Read() { // Read in the data synchronously. // see IDX_NAME, etc. for parameter indexes nsCOMPtr stmt; - nsresult rv = - mSyncConn->CreateStatement(NS_LITERAL_CSTRING("SELECT " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "originAttributes, " - "sameSite, " - "rawSameSite, " - "schemeMap " - "FROM moz_cookies"), - getter_AddRefs(stmt)); + nsresult rv = mSyncConn->CreateStatement(nsLiteralCString("SELECT " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "originAttributes, " + "sameSite, " + "rawSameSite, " + "schemeMap " + "FROM moz_cookies"), + getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, RESULT_RETRY); @@ -1821,60 +1789,59 @@ nsresult CookiePersistentStorage::InitDBConnInternal() { mDBConn->SetGrowthIncrement(512 * 1024, EmptyCString()); // make operations on the table asynchronous, for performance - mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF")); + mDBConn->ExecuteSimpleSQL("PRAGMA synchronous = OFF"_ns); // Use write-ahead-logging for performance. We cap the autocheckpoint limit at // 16 pages (around 500KB). - mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(MOZ_STORAGE_UNIQUIFY_QUERY_STR - "PRAGMA journal_mode = WAL")); - mDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA wal_autocheckpoint = 16")); + mDBConn->ExecuteSimpleSQL(nsLiteralCString(MOZ_STORAGE_UNIQUIFY_QUERY_STR + "PRAGMA journal_mode = WAL")); + mDBConn->ExecuteSimpleSQL("PRAGMA wal_autocheckpoint = 16"_ns); // cache frequently used statements (for insertion, deletion, and updating) - rv = mDBConn->CreateAsyncStatement( - NS_LITERAL_CSTRING("INSERT INTO moz_cookies (" - "originAttributes, " - "name, " - "value, " - "host, " - "path, " - "expiry, " - "lastAccessed, " - "creationTime, " - "isSecure, " - "isHttpOnly, " - "sameSite, " - "rawSameSite, " - "schemeMap " - ") VALUES (" - ":originAttributes, " - ":name, " - ":value, " - ":host, " - ":path, " - ":expiry, " - ":lastAccessed, " - ":creationTime, " - ":isSecure, " - ":isHttpOnly, " - ":sameSite, " - ":rawSameSite, " - ":schemeMap " - ")"), - getter_AddRefs(mStmtInsert)); + rv = + mDBConn->CreateAsyncStatement(nsLiteralCString("INSERT INTO moz_cookies (" + "originAttributes, " + "name, " + "value, " + "host, " + "path, " + "expiry, " + "lastAccessed, " + "creationTime, " + "isSecure, " + "isHttpOnly, " + "sameSite, " + "rawSameSite, " + "schemeMap " + ") VALUES (" + ":originAttributes, " + ":name, " + ":value, " + ":host, " + ":path, " + ":expiry, " + ":lastAccessed, " + ":creationTime, " + ":isSecure, " + ":isHttpOnly, " + ":sameSite, " + ":rawSameSite, " + ":schemeMap " + ")"), + getter_AddRefs(mStmtInsert)); NS_ENSURE_SUCCESS(rv, rv); rv = mDBConn->CreateAsyncStatement( - NS_LITERAL_CSTRING("DELETE FROM moz_cookies " - "WHERE name = :name AND host = :host AND path = :path " - "AND originAttributes = :originAttributes"), + nsLiteralCString("DELETE FROM moz_cookies " + "WHERE name = :name AND host = :host AND path = :path " + "AND originAttributes = :originAttributes"), getter_AddRefs(mStmtDelete)); NS_ENSURE_SUCCESS(rv, rv); rv = mDBConn->CreateAsyncStatement( - NS_LITERAL_CSTRING("UPDATE moz_cookies SET lastAccessed = :lastAccessed " - "WHERE name = :name AND host = :host AND path = :path " - "AND originAttributes = :originAttributes"), + nsLiteralCString("UPDATE moz_cookies SET lastAccessed = :lastAccessed " + "WHERE name = :name AND host = :host AND path = :path " + "AND originAttributes = :originAttributes"), getter_AddRefs(mStmtUpdate)); return rv; } @@ -1937,7 +1904,7 @@ nsresult CookiePersistentStorage::CreateTableForSchemaVersion6() { // We default originAttributes to empty string: this is so if users revert to // an older Firefox version that doesn't know about this field, any cookies // set will still work once they upgrade back. - rv = mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE moz_cookies (" "id INTEGER PRIMARY KEY, " "baseDomain TEXT, " @@ -1958,7 +1925,7 @@ nsresult CookiePersistentStorage::CreateTableForSchemaVersion6() { } // Create an index on baseDomain. - return mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + return mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, " "originAttributes)")); } @@ -1975,29 +1942,29 @@ nsresult CookiePersistentStorage::CreateTableForSchemaVersion5() { // users revert to an older Firefox version that doesn't know about these // fields, any cookies set will still work once they upgrade back. rv = mSyncConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE moz_cookies (" - "id INTEGER PRIMARY KEY, " - "baseDomain TEXT, " - "appId INTEGER DEFAULT 0, " - "inBrowserElement INTEGER DEFAULT 0, " - "name TEXT, " - "value TEXT, " - "host TEXT, " - "path TEXT, " - "expiry INTEGER, " - "lastAccessed INTEGER, " - "creationTime INTEGER, " - "isSecure INTEGER, " - "isHttpOnly INTEGER, " - "CONSTRAINT moz_uniqueid UNIQUE (name, host, path, " - "appId, inBrowserElement)" - ")")); + nsLiteralCString("CREATE TABLE moz_cookies (" + "id INTEGER PRIMARY KEY, " + "baseDomain TEXT, " + "appId INTEGER DEFAULT 0, " + "inBrowserElement INTEGER DEFAULT 0, " + "name TEXT, " + "value TEXT, " + "host TEXT, " + "path TEXT, " + "expiry INTEGER, " + "lastAccessed INTEGER, " + "creationTime INTEGER, " + "isSecure INTEGER, " + "isHttpOnly INTEGER, " + "CONSTRAINT moz_uniqueid UNIQUE (name, host, path, " + "appId, inBrowserElement)" + ")")); if (NS_FAILED(rv)) { return rv; } // Create an index on baseDomain. - return mSyncConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + return mSyncConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, " "appId, " "inBrowserElement)")); diff --git a/netwerk/cookie/CookieService.cpp b/netwerk/cookie/CookieService.cpp index aae796ec2d4c..ca7658b8a0ad 100644 --- a/netwerk/cookie/CookieService.cpp +++ b/netwerk/cookie/CookieService.cpp @@ -75,8 +75,7 @@ void ComposeCookieString(nsTArray& aCookieList, if (!cookie->Name().IsEmpty()) { // we have a name and value - write both - aCookieString += - cookie->Name() + NS_LITERAL_CSTRING("=") + cookie->Value(); + aCookieString += cookie->Name() + "="_ns + cookie->Value(); } else { // just write value aCookieString += cookie->Value(); @@ -1063,7 +1062,7 @@ bool CookieService::CanSetCookie( CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_OVERSIZE_CATEGORY, - NS_LITERAL_CSTRING("CookieOversize"), params); + "CookieOversize"_ns, params); return newCookie; } @@ -1387,7 +1386,7 @@ bool CookieService::ParseAttributes(nsIConsoleReportCollector* aCRC, } else { CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::infoFlag, CONSOLE_SAMESITE_CATEGORY, - NS_LITERAL_CSTRING("CookieSameSiteValueInvalid"), + "CookieSameSiteValueInvalid"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookieData.name())}); } } @@ -1407,7 +1406,7 @@ bool CookieService::ParseAttributes(nsIConsoleReportCollector* aCRC, StaticPrefs::network_cookie_sameSite_noneRequiresSecure()) { CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::infoFlag, CONSOLE_SAMESITE_CATEGORY, - NS_LITERAL_CSTRING("CookieRejectedNonRequiresSecure"), + "CookieRejectedNonRequiresSecure"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookieData.name())}); return newCookie; } @@ -1415,7 +1414,7 @@ bool CookieService::ParseAttributes(nsIConsoleReportCollector* aCRC, // if sameSite=lax by default is disabled, we want to warn the user. CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_SAMESITE_CATEGORY, - NS_LITERAL_CSTRING("CookieRejectedNonRequiresSecureForBeta"), + "CookieRejectedNonRequiresSecureForBeta"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookieData.name()), SAMESITE_MDN_URL}); } @@ -1425,13 +1424,12 @@ bool CookieService::ParseAttributes(nsIConsoleReportCollector* aCRC, if (laxByDefault) { CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::infoFlag, CONSOLE_SAMESITE_CATEGORY, - NS_LITERAL_CSTRING("CookieLaxForced"), + "CookieLaxForced"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookieData.name())}); } else { CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, - CONSOLE_SAMESITE_CATEGORY, - NS_LITERAL_CSTRING("CookieLaxForcedForBeta"), + CONSOLE_SAMESITE_CATEGORY, "CookieLaxForcedForBeta"_ns, AutoTArray{NS_ConvertUTF8toUTF16(aCookieData.name()), SAMESITE_MDN_URL}); } @@ -1738,7 +1736,7 @@ bool CookieService::CheckPath(CookieStruct& aCookieData, CookieLogging::LogMessageToConsole( aCRC, aHostURI, nsIScriptError::warningFlag, CONSOLE_OVERSIZE_CATEGORY, - NS_LITERAL_CSTRING("CookiePathOversize"), params); + "CookiePathOversize"_ns, params); return false; } diff --git a/netwerk/dns/GetAddrInfo.cpp b/netwerk/dns/GetAddrInfo.cpp index 907b08cca923..cb64b61ab27d 100644 --- a/netwerk/dns/GetAddrInfo.cpp +++ b/netwerk/dns/GetAddrInfo.cpp @@ -253,7 +253,7 @@ nsresult GetAddrInfo(const nsACString& aHost, uint16_t aAddressFamily, nsAutoCString host(aHost); if (gNativeIsLocalhost) { // pretend we use the given host but use IPv4 localhost instead! - host = NS_LITERAL_CSTRING("localhost"); + host = "localhost"_ns; aAddressFamily = PR_AF_INET; } diff --git a/netwerk/dns/TRR.cpp b/netwerk/dns/TRR.cpp index 3ec31db8c8e0..e77e0da298f7 100644 --- a/netwerk/dns/TRR.cpp +++ b/netwerk/dns/TRR.cpp @@ -304,9 +304,9 @@ nsresult TRR::SendHTTPRequest() { } if (query.IsEmpty()) { - query.Assign(NS_LITERAL_CSTRING("?dns=")); + query.Assign("?dns="_ns); } else { - query.Append(NS_LITERAL_CSTRING("&dns=")); + query.Append("&dns="_ns); } query.Append(body); @@ -353,9 +353,8 @@ nsresult TRR::SendHTTPRequest() { rv = httpChannel->SetTRRMode(nsIRequest::TRR_DISABLED_MODE); NS_ENSURE_SUCCESS(rv, rv); - rv = httpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Accept"), - NS_LITERAL_CSTRING("application/dns-message"), false); + rv = httpChannel->SetRequestHeader("Accept"_ns, "application/dns-message"_ns, + false); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString cred; @@ -363,8 +362,7 @@ nsresult TRR::SendHTTPRequest() { gTRRService->GetCredentials(cred); } if (!cred.IsEmpty()) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Authorization"), - cred, false); + rv = httpChannel->SetRequestHeader("Authorization"_ns, cred, false); NS_ENSURE_SUCCESS(rv, rv); } @@ -383,7 +381,7 @@ nsresult TRR::SendHTTPRequest() { mAllowRFC1918 = gTRRService->AllowRFC1918(); if (useGet) { - rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("GET")); + rv = httpChannel->SetRequestMethod("GET"_ns); NS_ENSURE_SUCCESS(rv, rv); } else { nsCOMPtr uploadChannel = do_QueryInterface(httpChannel); @@ -396,9 +394,9 @@ nsresult TRR::SendHTTPRequest() { NS_NewCStringInputStream(getter_AddRefs(uploadStream), std::move(body)); NS_ENSURE_SUCCESS(rv, rv); - rv = uploadChannel->ExplicitSetUploadStream( - uploadStream, NS_LITERAL_CSTRING("application/dns-message"), - streamLength, NS_LITERAL_CSTRING("POST"), false); + rv = uploadChannel->ExplicitSetUploadStream(uploadStream, + "application/dns-message"_ns, + streamLength, "POST"_ns, false); NS_ENSURE_SUCCESS(rv, rv); } @@ -428,35 +426,32 @@ nsresult TRR::SetupTRRServiceChannelInternal(nsIHttpChannel* aChannel, nsresult rv = NS_OK; if (!aUseGet) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Cache-Control"), - NS_LITERAL_CSTRING("no-store"), false); + rv = + httpChannel->SetRequestHeader("Cache-Control"_ns, "no-store"_ns, false); NS_ENSURE_SUCCESS(rv, rv); } // Sanitize the request by removing the Accept-Language header so we minimize // the amount of fingerprintable information we send to the server. if (!StaticPrefs::network_trr_send_accept_language_headers()) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Language"), - EmptyCString(), false); + rv = httpChannel->SetRequestHeader("Accept-Language"_ns, EmptyCString(), + false); NS_ENSURE_SUCCESS(rv, rv); } // Sanitize the request by removing the User-Agent if (!StaticPrefs::network_trr_send_user_agent_headers()) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("User-Agent"), - EmptyCString(), false); + rv = httpChannel->SetRequestHeader("User-Agent"_ns, EmptyCString(), false); NS_ENSURE_SUCCESS(rv, rv); } if (StaticPrefs::network_trr_send_empty_accept_encoding_headers()) { - rv = httpChannel->SetEmptyRequestHeader( - NS_LITERAL_CSTRING("Accept-Encoding")); + rv = httpChannel->SetEmptyRequestHeader("Accept-Encoding"_ns); NS_ENSURE_SUCCESS(rv, rv); } // set the *default* response content type - if (NS_FAILED(httpChannel->SetContentType( - NS_LITERAL_CSTRING("application/dns-message")))) { + if (NS_FAILED(httpChannel->SetContentType("application/dns-message"_ns))) { LOG(("TRR::SetupTRRServiceChannelInternal: couldn't set content-type!\n")); } diff --git a/netwerk/dns/TRRService.cpp b/netwerk/dns/TRRService.cpp index b7efc6a0b4bf..34a008a90987 100644 --- a/netwerk/dns/TRRService.cpp +++ b/netwerk/dns/TRRService.cpp @@ -48,7 +48,7 @@ TRRService::TRRService() : mInitialized(false), mTRRBlacklistExpireTime(72 * 3600), mLock("trrservice"), - mConfirmationNS(NS_LITERAL_CSTRING("example.com")), + mConfirmationNS("example.com"_ns), mWaitForCaptive(true), mRfc1918(false), mCaptiveIsPassed(false), diff --git a/netwerk/dns/nsDNSService2.cpp b/netwerk/dns/nsDNSService2.cpp index 65c1561d0ffb..e70dac294b9c 100644 --- a/netwerk/dns/nsDNSService2.cpp +++ b/netwerk/dns/nsDNSService2.cpp @@ -828,7 +828,7 @@ nsresult nsDNSService::PreprocessHostname(bool aLocalDomain, nsIIDNService* aIDN, nsACString& aACE) { // Enforce RFC 7686 - if (mBlockDotOnion && StringEndsWith(aInput, NS_LITERAL_CSTRING(".onion"))) { + if (mBlockDotOnion && StringEndsWith(aInput, ".onion"_ns)) { return NS_ERROR_UNKNOWN_HOST; } diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index b95ee173a306..ce3ab8b5550d 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -704,7 +704,7 @@ nsresult nsHostResolver::Init() { MOZ_ALWAYS_SUCCEEDS(threadPool->SetIdleThreadTimeout(poolTimeoutMs)); MOZ_ALWAYS_SUCCEEDS( threadPool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize)); - MOZ_ALWAYS_SUCCEEDS(threadPool->SetName(NS_LITERAL_CSTRING("DNS Resolver"))); + MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("DNS Resolver"_ns)); mResolverThreads = ToRefPtr(std::move(threadPool)); return NS_OK; diff --git a/netwerk/dns/nsIDNService.cpp b/netwerk/dns/nsIDNService.cpp index 715aef450781..3a0f32d2c67b 100644 --- a/netwerk/dns/nsIDNService.cpp +++ b/netwerk/dns/nsIDNService.cpp @@ -98,23 +98,23 @@ void nsIDNService::prefsChanged(const char* pref) { MOZ_ASSERT(NS_IsMainThread()); mLock.AssertCurrentThreadOwns(); - if (pref && NS_LITERAL_CSTRING(NS_NET_PREF_EXTRAALLOWED).Equals(pref)) { + if (pref && nsLiteralCString(NS_NET_PREF_EXTRAALLOWED).Equals(pref)) { InitializeBlocklist(mIDNBlocklist); } - if (pref && NS_LITERAL_CSTRING(NS_NET_PREF_EXTRABLOCKED).Equals(pref)) { + if (pref && nsLiteralCString(NS_NET_PREF_EXTRABLOCKED).Equals(pref)) { InitializeBlocklist(mIDNBlocklist); } - if (!pref || NS_LITERAL_CSTRING(NS_NET_PREF_SHOWPUNYCODE).Equals(pref)) { + if (!pref || nsLiteralCString(NS_NET_PREF_SHOWPUNYCODE).Equals(pref)) { bool val; if (NS_SUCCEEDED(Preferences::GetBool(NS_NET_PREF_SHOWPUNYCODE, &val))) mShowPunycode = val; } - if (!pref || NS_LITERAL_CSTRING(NS_NET_PREF_IDNUSEWHITELIST).Equals(pref)) { + if (!pref || nsLiteralCString(NS_NET_PREF_IDNUSEWHITELIST).Equals(pref)) { bool val; if (NS_SUCCEEDED(Preferences::GetBool(NS_NET_PREF_IDNUSEWHITELIST, &val))) mIDNUseWhitelist = val; } - if (!pref || NS_LITERAL_CSTRING(NS_NET_PREF_IDNRESTRICTION).Equals(pref)) { + if (!pref || nsLiteralCString(NS_NET_PREF_IDNRESTRICTION).Equals(pref)) { nsAutoCString profile; if (NS_FAILED( Preferences::GetCString(NS_NET_PREF_IDNRESTRICTION, profile))) { diff --git a/netwerk/ipc/DocumentLoadListener.cpp b/netwerk/ipc/DocumentLoadListener.cpp index 9fb8baaf5c11..05f12fc6d5f2 100644 --- a/netwerk/ipc/DocumentLoadListener.cpp +++ b/netwerk/ipc/DocumentLoadListener.cpp @@ -68,7 +68,7 @@ static void SetNeedToAddURIVisit(nsIChannel* aChannel, return; } - props->SetPropertyAsBool(NS_LITERAL_STRING("docshell.needToAddURIVisit"), + props->SetPropertyAsBool(u"docshell.needToAddURIVisit"_ns, aNeedToAddURIVisit); } @@ -1209,8 +1209,8 @@ static bool IsLargeAllocationLoad(CanonicalBrowsingContext* aBrowsingContext, } nsAutoCString ignoredHeaderValue; - nsresult rv = httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Large-Allocation"), ignoredHeaderValue); + nsresult rv = + httpChannel->GetResponseHeader("Large-Allocation"_ns, ignoredHeaderValue); if (NS_FAILED(rv)) { return false; } @@ -2038,7 +2038,7 @@ DocumentLoadListener::AsyncOnChannelRedirect( mChannel, getter_AddRefs(resultPrincipal)); if (NS_SUCCEEDED(rv)) { isHttpsOnlyExempt = nsContentUtils::IsExactSitePermAllow( - resultPrincipal, NS_LITERAL_CSTRING("https-only-mode-exception")); + resultPrincipal, "https-only-mode-exception"_ns); } } diff --git a/netwerk/protocol/about/nsAboutBlank.cpp b/netwerk/protocol/about/nsAboutBlank.cpp index 593b18b1ac1a..6afe3eb3445f 100644 --- a/netwerk/protocol/about/nsAboutBlank.cpp +++ b/netwerk/protocol/about/nsAboutBlank.cpp @@ -20,9 +20,9 @@ nsAboutBlank::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, if (NS_FAILED(rv)) return rv; nsCOMPtr channel; - rv = NS_NewInputStreamChannelInternal( - getter_AddRefs(channel), aURI, in.forget(), - NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8"), aLoadInfo); + rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel), aURI, + in.forget(), "text/html"_ns, "utf-8"_ns, + aLoadInfo); if (NS_FAILED(rv)) return rv; channel.forget(result); diff --git a/netwerk/protocol/about/nsAboutCache.cpp b/netwerk/protocol/about/nsAboutCache.cpp index 55c8749291aa..6bc19ed7a8d5 100644 --- a/netwerk/protocol/about/nsAboutCache.cpp +++ b/netwerk/protocol/about/nsAboutCache.cpp @@ -63,9 +63,9 @@ nsresult nsAboutCache::Channel::Init(nsIURI* aURI, nsILoadInfo* aLoadInfo) { mOverview = storageName.IsEmpty(); if (mOverview) { // ...and visit all we can - mStorageList.AppendElement(NS_LITERAL_CSTRING("memory")); - mStorageList.AppendElement(NS_LITERAL_CSTRING("disk")); - mStorageList.AppendElement(NS_LITERAL_CSTRING("appcache")); + mStorageList.AppendElement("memory"_ns); + mStorageList.AppendElement("disk"_ns); + mStorageList.AppendElement("appcache"_ns); } else { // ...and visit just the specified storage, entries will output too mStorageList.AppendElement(storageName); @@ -74,9 +74,9 @@ nsresult nsAboutCache::Channel::Init(nsIURI* aURI, nsILoadInfo* aLoadInfo) { // The entries header is added on encounter of the first entry mEntriesHeaderAdded = false; - rv = NS_NewInputStreamChannelInternal( - getter_AddRefs(mChannel), aURI, inputStream.forget(), - NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8"), aLoadInfo); + rv = NS_NewInputStreamChannelInternal(getter_AddRefs(mChannel), aURI, + inputStream.forget(), "text/html"_ns, + "utf-8"_ns, aLoadInfo); if (NS_FAILED(rv)) return rv; mBuffer.AssignLiteral( @@ -147,7 +147,7 @@ nsresult nsAboutCache::Channel::ParseURI(nsIURI* uri, nsACString& storage) { if (NS_FAILED(rv)) return rv; mContextString.Truncate(); - mLoadInfo = CacheFileUtils::ParseKey(NS_LITERAL_CSTRING("")); + mLoadInfo = CacheFileUtils::ParseKey(""_ns); storage.Truncate(); nsACString::const_iterator start, valueStart, end; @@ -155,7 +155,7 @@ nsresult nsAboutCache::Channel::ParseURI(nsIURI* uri, nsACString& storage) { path.EndReading(end); valueStart = end; - if (!FindInReadable(NS_LITERAL_CSTRING("?storage="), start, valueStart)) { + if (!FindInReadable("?storage="_ns, start, valueStart)) { return NS_OK; } @@ -163,8 +163,7 @@ nsresult nsAboutCache::Channel::ParseURI(nsIURI* uri, nsACString& storage) { start = valueStart; valueStart = end; - if (!FindInReadable(NS_LITERAL_CSTRING("&context="), start, valueStart)) - start = end; + if (!FindInReadable("&context="_ns, start, valueStart)) start = end; nsACString::const_iterator storageNameEnd = start; diff --git a/netwerk/protocol/about/nsAboutCacheEntry.cpp b/netwerk/protocol/about/nsAboutCacheEntry.cpp index e13ed1ab2d24..ff2984b66b38 100644 --- a/netwerk/protocol/about/nsAboutCacheEntry.cpp +++ b/netwerk/protocol/about/nsAboutCacheEntry.cpp @@ -119,9 +119,9 @@ nsresult nsAboutCacheEntry::Channel::Init(nsIURI* uri, nsILoadInfo* aLoadInfo) { rv = GetContentStream(uri, getter_AddRefs(stream)); if (NS_FAILED(rv)) return rv; - rv = NS_NewInputStreamChannelInternal( - getter_AddRefs(mChannel), uri, stream.forget(), - NS_LITERAL_CSTRING("text/html"), NS_LITERAL_CSTRING("utf-8"), aLoadInfo); + rv = NS_NewInputStreamChannelInternal(getter_AddRefs(mChannel), uri, + stream.forget(), "text/html"_ns, + "utf-8"_ns, aLoadInfo); if (NS_FAILED(rv)) return rv; return NS_OK; @@ -211,14 +211,14 @@ nsresult nsAboutCacheEntry::Channel::ParseURI(nsIURI* uri, keyBegin = begin; keyEnd = end; - if (!FindInReadable(NS_LITERAL_CSTRING("?storage="), keyBegin, keyEnd)) + if (!FindInReadable("?storage="_ns, keyBegin, keyEnd)) return NS_ERROR_FAILURE; valBegin = keyEnd; // the value of the storage key starts after the key keyBegin = keyEnd; keyEnd = end; - if (!FindInReadable(NS_LITERAL_CSTRING("&context="), keyBegin, keyEnd)) + if (!FindInReadable("&context="_ns, keyBegin, keyEnd)) return NS_ERROR_FAILURE; storageName.Assign(Substring(valBegin, keyBegin)); @@ -226,16 +226,14 @@ nsresult nsAboutCacheEntry::Channel::ParseURI(nsIURI* uri, keyBegin = keyEnd; keyEnd = end; - if (!FindInReadable(NS_LITERAL_CSTRING("&eid="), keyBegin, keyEnd)) - return NS_ERROR_FAILURE; + if (!FindInReadable("&eid="_ns, keyBegin, keyEnd)) return NS_ERROR_FAILURE; nsAutoCString contextKey(Substring(valBegin, keyBegin)); valBegin = keyEnd; // the value of the eid key starts after the key keyBegin = keyEnd; keyEnd = end; - if (!FindInReadable(NS_LITERAL_CSTRING("&uri="), keyBegin, keyEnd)) - return NS_ERROR_FAILURE; + if (!FindInReadable("&uri="_ns, keyBegin, keyEnd)) return NS_ERROR_FAILURE; enahnceID.Assign(Substring(valBegin, keyBegin)); diff --git a/netwerk/protocol/about/nsAboutProtocolHandler.cpp b/netwerk/protocol/about/nsAboutProtocolHandler.cpp index 0a83c92afa6d..84727004f9d7 100644 --- a/netwerk/protocol/about/nsAboutProtocolHandler.cpp +++ b/netwerk/protocol/about/nsAboutProtocolHandler.cpp @@ -237,11 +237,10 @@ nsAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo, "nsIAboutModule->newChannel(aURI, aLoadInfo) needs to " "set LoadInfo"); AutoTArray params = { - NS_LITERAL_STRING("nsIAboutModule->newChannel(aURI)"), - NS_LITERAL_STRING("nsIAboutModule->newChannel(aURI, aLoadInfo)")}; + u"nsIAboutModule->newChannel(aURI)"_ns, + u"nsIAboutModule->newChannel(aURI, aLoadInfo)"_ns}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("Security by Default"), + nsIScriptError::warningFlag, "Security by Default"_ns, nullptr, // aDocument nsContentUtils::eNECKO_PROPERTIES, "APIDeprecationWarning", params); (*result)->SetLoadInfo(aLoadInfo); @@ -263,7 +262,7 @@ nsAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo, nsCOMPtr writableBag = do_QueryInterface(*result); if (writableBag) { - writableBag->SetPropertyAsInterface(NS_LITERAL_STRING("baseURI"), + writableBag->SetPropertyAsInterface(u"baseURI"_ns, aboutURI->GetBaseURI()); } } diff --git a/netwerk/protocol/about/nsAboutProtocolUtils.h b/netwerk/protocol/about/nsAboutProtocolUtils.h index 7b16e71fafc5..ef508dce2e2c 100644 --- a/netwerk/protocol/about/nsAboutProtocolUtils.h +++ b/netwerk/protocol/about/nsAboutProtocolUtils.h @@ -20,7 +20,7 @@ nsresult rv = aAboutURI->GetPathQueryRef(aModule); NS_ENSURE_SUCCESS(rv, rv); - int32_t f = aModule.FindCharInSet(NS_LITERAL_CSTRING("#?")); + int32_t f = aModule.FindCharInSet("#?"_ns); if (f != kNotFound) { aModule.Truncate(f); } diff --git a/netwerk/protocol/file/nsFileChannel.cpp b/netwerk/protocol/file/nsFileChannel.cpp index df4040aad0f5..b40e66d0afaf 100644 --- a/netwerk/protocol/file/nsFileChannel.cpp +++ b/netwerk/protocol/file/nsFileChannel.cpp @@ -377,7 +377,7 @@ nsresult nsFileChannel::OpenContentStream(bool async, nsIInputStream** result, // sniffer code in nsBaseChannel. // However, don't override explicitly set types. if (!HasContentTypeHint()) - SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM)); + SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM)); } else { nsAutoCString contentType; rv = MakeFileInputStream(file, stream, contentType, async); diff --git a/netwerk/protocol/file/nsFileProtocolHandler.cpp b/netwerk/protocol/file/nsFileProtocolHandler.cpp index 53aee23b3533..31c8aa8e625c 100644 --- a/netwerk/protocol/file/nsFileProtocolHandler.cpp +++ b/netwerk/protocol/file/nsFileProtocolHandler.cpp @@ -92,8 +92,7 @@ nsFileProtocolHandler::ReadURLFile(nsIFile* aFile, nsIURI** aURI) { // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s02.html nsAutoCString leafName; nsresult rv = aFile->GetNativeLeafName(leafName); - if (NS_FAILED(rv) || - !StringEndsWith(leafName, NS_LITERAL_CSTRING(".desktop"))) + if (NS_FAILED(rv) || !StringEndsWith(leafName, ".desktop"_ns)) return NS_ERROR_NOT_AVAILABLE; bool isFile = false; diff --git a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp index c2212e09f5d3..8975545e5c27 100644 --- a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp +++ b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp @@ -259,7 +259,7 @@ nsresult nsFtpState::EstablishControlConnection() { mTryingCachedControl = true; // we have to set charset to connection if server supports utf-8 - if (mUseUTF8) mChannel->SetContentCharset(NS_LITERAL_CSTRING("UTF-8")); + if (mUseUTF8) mChannel->SetContentCharset("UTF-8"_ns); // we're already connected to this server, skip login. mState = FTP_S_PASV; @@ -800,7 +800,7 @@ nsFtpState::R_pass() { } nsresult nsFtpState::S_pwd() { - return SendFTPCommand(NS_LITERAL_CSTRING("PWD" CRLF)); + return SendFTPCommand(nsLiteralCString("PWD" CRLF)); } FTP_STATE @@ -825,7 +825,7 @@ nsFtpState::R_pwd() { } nsresult nsFtpState::S_syst() { - return SendFTPCommand(NS_LITERAL_CSTRING("SYST" CRLF)); + return SendFTPCommand(nsLiteralCString("SYST" CRLF)); } FTP_STATE @@ -867,7 +867,7 @@ nsFtpState::R_syst() { } nsresult nsFtpState::S_acct() { - return SendFTPCommand(NS_LITERAL_CSTRING("ACCT noaccount" CRLF)); + return SendFTPCommand(nsLiteralCString("ACCT noaccount" CRLF)); } FTP_STATE @@ -878,7 +878,7 @@ nsFtpState::R_acct() { } nsresult nsFtpState::S_type() { - return SendFTPCommand(NS_LITERAL_CSTRING("TYPE I" CRLF)); + return SendFTPCommand(nsLiteralCString("TYPE I" CRLF)); } FTP_STATE @@ -1022,7 +1022,7 @@ nsresult nsFtpState::SetContentType() { } } return mChannel->SetContentType( - NS_LITERAL_CSTRING(APPLICATION_HTTP_INDEX_FORMAT)); + nsLiteralCString(APPLICATION_HTTP_INDEX_FORMAT)); } nsresult nsFtpState::S_list() { @@ -1101,7 +1101,7 @@ nsFtpState::R_retr() { } if (mResponseCode / 100 == 1) { - mChannel->SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM)); + mChannel->SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM)); Telemetry::ScalarAdd( Telemetry::ScalarID::NETWORKING_FTP_OPENED_CHANNELS_FILES, 1); @@ -1435,15 +1435,15 @@ nsFtpState::R_pasv() { } nsresult nsFtpState::S_feat() { - return SendFTPCommand(NS_LITERAL_CSTRING("FEAT" CRLF)); + return SendFTPCommand(nsLiteralCString("FEAT" CRLF)); } FTP_STATE nsFtpState::R_feat() { if (mResponseCode / 100 == 2) { - if (mResponseMsg.Find(NS_LITERAL_CSTRING(CRLF " UTF8" CRLF), true) > -1) { + if (mResponseMsg.Find(nsLiteralCString(CRLF " UTF8" CRLF), true) > -1) { // This FTP server supports UTF-8 encoding - mChannel->SetContentCharset(NS_LITERAL_CSTRING("UTF-8")); + mChannel->SetContentCharset("UTF-8"_ns); mUseUTF8 = true; return FTP_S_OPTS; } @@ -1455,7 +1455,7 @@ nsFtpState::R_feat() { nsresult nsFtpState::S_opts() { // This command is for compatibility of old FTP spec (IETF Draft) - return SendFTPCommand(NS_LITERAL_CSTRING("OPTS UTF8 ON" CRLF)); + return SendFTPCommand(nsLiteralCString("OPTS UTF8 ON" CRLF)); } FTP_STATE @@ -1659,8 +1659,7 @@ nsresult nsFtpState::SendFTPCommand(const nsACString& command) { // we don't want to log the password: nsAutoCString logcmd(command); - if (StringBeginsWith(command, NS_LITERAL_CSTRING("PASS "))) - logcmd = "PASS xxxxx"; + if (StringBeginsWith(command, "PASS "_ns)) logcmd = "PASS xxxxx"; LOG(("FTP:(%p) writing \"%s\"\n", this, logcmd.get())); diff --git a/netwerk/protocol/gio/nsGIOProtocolHandler.cpp b/netwerk/protocol/gio/nsGIOProtocolHandler.cpp index 4f66103d2f61..60624f6d0353 100644 --- a/netwerk/protocol/gio/nsGIOProtocolHandler.cpp +++ b/netwerk/protocol/gio/nsGIOProtocolHandler.cpp @@ -960,11 +960,10 @@ nsGIOProtocolHandler::NewChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, } RefPtr tmpStream = stream; - rv = - NS_NewInputStreamChannelInternal(aResult, aURI, tmpStream.forget(), - NS_LITERAL_CSTRING(UNKNOWN_CONTENT_TYPE), - EmptyCString(), // aContentCharset - aLoadInfo); + rv = NS_NewInputStreamChannelInternal(aResult, aURI, tmpStream.forget(), + nsLiteralCString(UNKNOWN_CONTENT_TYPE), + EmptyCString(), // aContentCharset + aLoadInfo); if (NS_SUCCEEDED(rv)) { stream->SetChannel(*aResult); } diff --git a/netwerk/protocol/http/ASpdySession.cpp b/netwerk/protocol/http/ASpdySession.cpp index a37f366d4f31..2d1cd78afc94 100644 --- a/netwerk/protocol/http/ASpdySession.cpp +++ b/netwerk/protocol/http/ASpdySession.cpp @@ -43,7 +43,7 @@ SpdyInformation::SpdyInformation() { // highest index of enabled protocols is the // most preferred for ALPN negotiaton Version[0] = SpdyVersion::HTTP_2; - VersionString[0] = NS_LITERAL_CSTRING("h2"); + VersionString[0] = "h2"_ns; ALPNCallbacks[0] = Http2Session::ALPNCallback; } diff --git a/netwerk/protocol/http/AlternateServices.cpp b/netwerk/protocol/http/AlternateServices.cpp index 68a3a907593f..9afb67e3fe55 100644 --- a/netwerk/protocol/http/AlternateServices.cpp +++ b/netwerk/protocol/http/AlternateServices.cpp @@ -368,7 +368,7 @@ void AltSvcMapping::GetConnectionInfo( void AltSvcMapping::Serialize(nsCString& out) { // Be careful, when serializing new members, add them to the end of this list. - out = mHttps ? NS_LITERAL_CSTRING("https:") : NS_LITERAL_CSTRING("http:"); + out = mHttps ? "https:"_ns : "http:"_ns; out.Append(mOriginHost); out.Append(':'); out.AppendInt(mOriginPort); @@ -472,11 +472,9 @@ AltSvcMapping::AltSvcMapping(DataStorage* storage, int32_t epoch, // Add code to deserialize new members here! #undef _NS_NEXT_TOKEN - MakeHashKey( - mHashKey, - mHttps ? NS_LITERAL_CSTRING("https") : NS_LITERAL_CSTRING("http"), - mOriginHost, mOriginPort, mPrivate, mIsolated, mTopWindowOrigin, - mOriginAttributes); + MakeHashKey(mHashKey, mHttps ? "https"_ns : "http"_ns, mOriginHost, + mOriginPort, mPrivate, mIsolated, mTopWindowOrigin, + mOriginAttributes); } while (false); } @@ -1069,7 +1067,7 @@ void AltSvcCache::UpdateAltServiceMapping( } } else { // for http:// resources we fetch .well-known too - nsAutoCString origin(NS_LITERAL_CSTRING("http://")); + nsAutoCString origin("http://"_ns); // Check whether origin is an ipv6 address. In that case we need to add // '[]'. diff --git a/netwerk/protocol/http/Http2Compression.cpp b/netwerk/protocol/http/Http2Compression.cpp index 9d55a8327e3e..6ed2715c4d26 100644 --- a/netwerk/protocol/http/Http2Compression.cpp +++ b/netwerk/protocol/http/Http2Compression.cpp @@ -107,70 +107,67 @@ static void InitializeStaticHeaders() { gStaticHeaders = new nsDeque(); gStaticReporter = new HpackStaticTableReporter(); RegisterStrongMemoryReporter(gStaticReporter); - AddStaticElement(NS_LITERAL_CSTRING(":authority")); - AddStaticElement(NS_LITERAL_CSTRING(":method"), NS_LITERAL_CSTRING("GET")); - AddStaticElement(NS_LITERAL_CSTRING(":method"), NS_LITERAL_CSTRING("POST")); - AddStaticElement(NS_LITERAL_CSTRING(":path"), NS_LITERAL_CSTRING("/")); - AddStaticElement(NS_LITERAL_CSTRING(":path"), - NS_LITERAL_CSTRING("/index.html")); - AddStaticElement(NS_LITERAL_CSTRING(":scheme"), NS_LITERAL_CSTRING("http")); - AddStaticElement(NS_LITERAL_CSTRING(":scheme"), - NS_LITERAL_CSTRING("https")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("200")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("204")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("206")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("304")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("400")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("404")); - AddStaticElement(NS_LITERAL_CSTRING(":status"), NS_LITERAL_CSTRING("500")); - AddStaticElement(NS_LITERAL_CSTRING("accept-charset")); - AddStaticElement(NS_LITERAL_CSTRING("accept-encoding"), - NS_LITERAL_CSTRING("gzip, deflate")); - AddStaticElement(NS_LITERAL_CSTRING("accept-language")); - AddStaticElement(NS_LITERAL_CSTRING("accept-ranges")); - AddStaticElement(NS_LITERAL_CSTRING("accept")); - AddStaticElement(NS_LITERAL_CSTRING("access-control-allow-origin")); - AddStaticElement(NS_LITERAL_CSTRING("age")); - AddStaticElement(NS_LITERAL_CSTRING("allow")); - AddStaticElement(NS_LITERAL_CSTRING("authorization")); - AddStaticElement(NS_LITERAL_CSTRING("cache-control")); - AddStaticElement(NS_LITERAL_CSTRING("content-disposition")); - AddStaticElement(NS_LITERAL_CSTRING("content-encoding")); - AddStaticElement(NS_LITERAL_CSTRING("content-language")); - AddStaticElement(NS_LITERAL_CSTRING("content-length")); - AddStaticElement(NS_LITERAL_CSTRING("content-location")); - AddStaticElement(NS_LITERAL_CSTRING("content-range")); - AddStaticElement(NS_LITERAL_CSTRING("content-type")); - AddStaticElement(NS_LITERAL_CSTRING("cookie")); - AddStaticElement(NS_LITERAL_CSTRING("date")); - AddStaticElement(NS_LITERAL_CSTRING("etag")); - AddStaticElement(NS_LITERAL_CSTRING("expect")); - AddStaticElement(NS_LITERAL_CSTRING("expires")); - AddStaticElement(NS_LITERAL_CSTRING("from")); - AddStaticElement(NS_LITERAL_CSTRING("host")); - AddStaticElement(NS_LITERAL_CSTRING("if-match")); - AddStaticElement(NS_LITERAL_CSTRING("if-modified-since")); - AddStaticElement(NS_LITERAL_CSTRING("if-none-match")); - AddStaticElement(NS_LITERAL_CSTRING("if-range")); - AddStaticElement(NS_LITERAL_CSTRING("if-unmodified-since")); - AddStaticElement(NS_LITERAL_CSTRING("last-modified")); - AddStaticElement(NS_LITERAL_CSTRING("link")); - AddStaticElement(NS_LITERAL_CSTRING("location")); - AddStaticElement(NS_LITERAL_CSTRING("max-forwards")); - AddStaticElement(NS_LITERAL_CSTRING("proxy-authenticate")); - AddStaticElement(NS_LITERAL_CSTRING("proxy-authorization")); - AddStaticElement(NS_LITERAL_CSTRING("range")); - AddStaticElement(NS_LITERAL_CSTRING("referer")); - AddStaticElement(NS_LITERAL_CSTRING("refresh")); - AddStaticElement(NS_LITERAL_CSTRING("retry-after")); - AddStaticElement(NS_LITERAL_CSTRING("server")); - AddStaticElement(NS_LITERAL_CSTRING("set-cookie")); - AddStaticElement(NS_LITERAL_CSTRING("strict-transport-security")); - AddStaticElement(NS_LITERAL_CSTRING("transfer-encoding")); - AddStaticElement(NS_LITERAL_CSTRING("user-agent")); - AddStaticElement(NS_LITERAL_CSTRING("vary")); - AddStaticElement(NS_LITERAL_CSTRING("via")); - AddStaticElement(NS_LITERAL_CSTRING("www-authenticate")); + AddStaticElement(":authority"_ns); + AddStaticElement(":method"_ns, "GET"_ns); + AddStaticElement(":method"_ns, "POST"_ns); + AddStaticElement(":path"_ns, "/"_ns); + AddStaticElement(":path"_ns, "/index.html"_ns); + AddStaticElement(":scheme"_ns, "http"_ns); + AddStaticElement(":scheme"_ns, "https"_ns); + AddStaticElement(":status"_ns, "200"_ns); + AddStaticElement(":status"_ns, "204"_ns); + AddStaticElement(":status"_ns, "206"_ns); + AddStaticElement(":status"_ns, "304"_ns); + AddStaticElement(":status"_ns, "400"_ns); + AddStaticElement(":status"_ns, "404"_ns); + AddStaticElement(":status"_ns, "500"_ns); + AddStaticElement("accept-charset"_ns); + AddStaticElement("accept-encoding"_ns, "gzip, deflate"_ns); + AddStaticElement("accept-language"_ns); + AddStaticElement("accept-ranges"_ns); + AddStaticElement("accept"_ns); + AddStaticElement("access-control-allow-origin"_ns); + AddStaticElement("age"_ns); + AddStaticElement("allow"_ns); + AddStaticElement("authorization"_ns); + AddStaticElement("cache-control"_ns); + AddStaticElement("content-disposition"_ns); + AddStaticElement("content-encoding"_ns); + AddStaticElement("content-language"_ns); + AddStaticElement("content-length"_ns); + AddStaticElement("content-location"_ns); + AddStaticElement("content-range"_ns); + AddStaticElement("content-type"_ns); + AddStaticElement("cookie"_ns); + AddStaticElement("date"_ns); + AddStaticElement("etag"_ns); + AddStaticElement("expect"_ns); + AddStaticElement("expires"_ns); + AddStaticElement("from"_ns); + AddStaticElement("host"_ns); + AddStaticElement("if-match"_ns); + AddStaticElement("if-modified-since"_ns); + AddStaticElement("if-none-match"_ns); + AddStaticElement("if-range"_ns); + AddStaticElement("if-unmodified-since"_ns); + AddStaticElement("last-modified"_ns); + AddStaticElement("link"_ns); + AddStaticElement("location"_ns); + AddStaticElement("max-forwards"_ns); + AddStaticElement("proxy-authenticate"_ns); + AddStaticElement("proxy-authorization"_ns); + AddStaticElement("range"_ns); + AddStaticElement("referer"_ns); + AddStaticElement("refresh"_ns); + AddStaticElement("retry-after"_ns); + AddStaticElement("server"_ns); + AddStaticElement("set-cookie"_ns); + AddStaticElement("strict-transport-security"_ns); + AddStaticElement("transfer-encoding"_ns); + AddStaticElement("user-agent"_ns); + AddStaticElement("vary"_ns); + AddStaticElement("via"_ns); + AddStaticElement("www-authenticate"_ns); } } @@ -546,7 +543,7 @@ nsresult Http2Decompressor::OutputHeader(const nsACString& name, // Status comes first if (name.EqualsLiteral(":status")) { - nsAutoCString status(NS_LITERAL_CSTRING("HTTP/2 ")); + nsAutoCString status("HTTP/2 "_ns); status.Append(value); status.AppendLiteral("\r\n"); mOutput->Insert(status, 0); @@ -1067,17 +1064,16 @@ nsresult Http2Compressor::EncodeHeaderBlock( // colon headers first if (!simpleConnectForm) { - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":method"), method), false, false); - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":path"), path), true, false); - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":authority"), host), false, false); - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":scheme"), scheme), false, false); + ProcessHeader(nvPair(":method"_ns, method), false, false); + ProcessHeader(nvPair(":path"_ns, path), true, false); + ProcessHeader(nvPair(":authority"_ns, host), false, false); + ProcessHeader(nvPair(":scheme"_ns, scheme), false, false); if (isWebsocket) { - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":protocol"), protocol), false, - false); + ProcessHeader(nvPair(":protocol"_ns, protocol), false, false); } } else { - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":method"), method), false, false); - ProcessHeader(nvPair(NS_LITERAL_CSTRING(":authority"), host), false, false); + ProcessHeader(nvPair(":method"_ns, method), false, false); + ProcessHeader(nvPair(":authority"_ns, host), false, false); } // now the non colon headers diff --git a/netwerk/protocol/http/Http3Session.cpp b/netwerk/protocol/http/Http3Session.cpp index 4728c3f65d6e..890b528526fd 100644 --- a/netwerk/protocol/http/Http3Session.cpp +++ b/netwerk/protocol/http/Http3Session.cpp @@ -913,8 +913,8 @@ void Http3Session::Close(nsresult aReason) { mError = aReason; // If necko closes connection, this will map to "closing" key and 37 in the // graph. - Telemetry::Accumulate(Telemetry::HTTP3_CONNECTTION_CLOSE_CODE, - NS_LITERAL_CSTRING("closing"), 37); + Telemetry::Accumulate(Telemetry::HTTP3_CONNECTTION_CLOSE_CODE, "closing"_ns, + 37); CloseInternal(true); } @@ -1390,10 +1390,8 @@ void Http3Session::CloseConnectionTelemetry(CloseError& aError, bool aClosing) { // in the later case itt will change to closed. In tthis way we can // distinguish which side is closing connecttion first. If necko closes // connection, this will map to "closing" key and 37 in the graph. - Telemetry::Accumulate( - Telemetry::HTTP3_CONNECTTION_CLOSE_CODE, - aClosing ? NS_LITERAL_CSTRING("closing") : NS_LITERAL_CSTRING("closed"), - value); + Telemetry::Accumulate(Telemetry::HTTP3_CONNECTTION_CLOSE_CODE, + aClosing ? "closing"_ns : "closed"_ns, value); } } // namespace net diff --git a/netwerk/protocol/http/HttpBaseChannel.cpp b/netwerk/protocol/http/HttpBaseChannel.cpp index f276046cdf46..c10128acfa2f 100644 --- a/netwerk/protocol/http/HttpBaseChannel.cpp +++ b/netwerk/protocol/http/HttpBaseChannel.cpp @@ -507,8 +507,7 @@ HttpBaseChannel::SetDocshellUserAgentOverride() { } NS_ConvertUTF16toUTF8 utf8CustomUserAgent(customUserAgent); - nsresult rv = SetRequestHeader(NS_LITERAL_CSTRING("User-Agent"), - utf8CustomUserAgent, false); + nsresult rv = SetRequestHeader("User-Agent"_ns, utf8CustomUserAgent, false); if (NS_FAILED(rv)) return rv; return NS_OK; @@ -798,7 +797,7 @@ HttpBaseChannel::SetUploadStream(nsIInputStream* stream, nsCString contentType(contentTypeArg); if (contentType.IsEmpty()) { contentType.SetIsVoid(true); - method = NS_LITERAL_CSTRING("POST"); + method = "POST"_ns; // MIME streams are a special case, and include headers which need to be // copied to the channel. @@ -815,7 +814,7 @@ HttpBaseChannel::SetUploadStream(nsIInputStream* stream, hasHeaders = true; } else { - method = NS_LITERAL_CSTRING("PUT"); + method = "PUT"_ns; MOZ_ASSERT( NS_FAILED(CallQueryInterface(stream, getter_AddRefs(mimeStream))), @@ -828,7 +827,7 @@ HttpBaseChannel::SetUploadStream(nsIInputStream* stream, // if stream is null, ExplicitSetUploadStream returns error. // So we need special case for GET method. mUploadStreamHasHeaders = false; - mRequestHead.SetMethod(NS_LITERAL_CSTRING("GET")); // revert to GET request + mRequestHead.SetMethod("GET"_ns); // revert to GET request mUploadStream = stream; return NS_OK; } @@ -996,9 +995,9 @@ HttpBaseChannel::ExplicitSetUploadStream(nsIInputStream* aStream, if (!aStreamHasHeaders && !aContentType.IsVoid()) { if (aContentType.IsEmpty()) { - SetEmptyRequestHeader(NS_LITERAL_CSTRING("Content-Type")); + SetEmptyRequestHeader("Content-Type"_ns); } else { - SetRequestHeader(NS_LITERAL_CSTRING("Content-Type"), aContentType, false); + SetRequestHeader("Content-Type"_ns, aContentType, false); } } @@ -1324,15 +1323,14 @@ HttpBaseChannel::nsContentEncodings::GetNext(nsACString& aNextEncoding) { encoding.EndReading(end); bool haveType = false; - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("gzip"), start, end)) { + if (CaseInsensitiveFindInReadable("gzip"_ns, start, end)) { aNextEncoding.AssignLiteral(APPLICATION_GZIP); haveType = true; } if (!haveType) { encoding.BeginReading(start); - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("compress"), start, - end)) { + if (CaseInsensitiveFindInReadable("compress"_ns, start, end)) { aNextEncoding.AssignLiteral(APPLICATION_COMPRESS); haveType = true; } @@ -1340,8 +1338,7 @@ HttpBaseChannel::nsContentEncodings::GetNext(nsACString& aNextEncoding) { if (!haveType) { encoding.BeginReading(start); - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("deflate"), start, - end)) { + if (CaseInsensitiveFindInReadable("deflate"_ns, start, end)) { aNextEncoding.AssignLiteral(APPLICATION_ZIP); haveType = true; } @@ -1349,7 +1346,7 @@ HttpBaseChannel::nsContentEncodings::GetNext(nsACString& aNextEncoding) { if (!haveType) { encoding.BeginReading(start); - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("br"), start, end)) { + if (CaseInsensitiveFindInReadable("br"_ns, start, end)) { aNextEncoding.AssignLiteral(APPLICATION_BROTLI); haveType = true; } @@ -2201,7 +2198,7 @@ nsresult HttpBaseChannel::ProcessCrossOriginResourcePolicyHeader() { // indicates. We might want to make that stricter. if (content.IsEmpty() && mLoadInfo->GetLoadingEmbedderPolicy() == nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP) { - content = NS_LITERAL_CSTRING("same-origin"); + content = "same-origin"_ns; } } @@ -3413,8 +3410,7 @@ HttpBaseChannel::CloneReplacementChannelConfig(bool aPreserveMethod, } else { dom::ReferrerPolicy referrerPolicy = dom::ReferrerPolicy::_empty; nsAutoCString tRPHeaderCValue; - Unused << GetResponseHeader(NS_LITERAL_CSTRING("referrer-policy"), - tRPHeaderCValue); + Unused << GetResponseHeader("referrer-policy"_ns, tRPHeaderCValue); NS_ConvertUTF8toUTF16 tRPHeaderValue(tRPHeaderCValue); if (!tRPHeaderValue.IsEmpty()) { @@ -3648,7 +3644,7 @@ HttpBaseChannel::CloneReplacementChannelConfig(bool aPreserveMethod, if (config.contentType) { ctype = *config.contentType; } else { - ctype = NS_LITERAL_CSTRING("application/octet-stream"); + ctype = "application/octet-stream"_ns; } if (config.contentLength && !config.contentLength->IsEmpty()) { uploadChannel->SetUploadStream( @@ -3805,8 +3801,7 @@ nsresult HttpBaseChannel::SetupReplacementChannel(nsIURI* newURI, nsAutoCString oldAcceptValue; nsresult hasHeader = mRequestHead.GetHeader(nsHttp::Accept, oldAcceptValue); if (NS_SUCCEEDED(hasHeader)) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), - oldAcceptValue, false); + rv = httpChannel->SetRequestHeader("Accept"_ns, oldAcceptValue, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -3819,8 +3814,7 @@ nsresult HttpBaseChannel::SetupReplacementChannel(nsIURI* newURI, nsresult hasHeader = mRequestHead.GetHeader(nsHttp::User_Agent, oldUserAgent); if (NS_SUCCEEDED(hasHeader)) { - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("User-Agent"), - oldUserAgent, false); + rv = httpChannel->SetRequestHeader("User-Agent"_ns, oldUserAgent, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -4159,8 +4153,7 @@ HttpBaseChannel::TimingAllowCheck(nsIPrincipal* aOrigin, bool* _retval) { } nsAutoCString headerValue; - rv = - GetResponseHeader(NS_LITERAL_CSTRING("Timing-Allow-Origin"), headerValue); + rv = GetResponseHeader("Timing-Allow-Origin"_ns, headerValue); if (NS_FAILED(rv)) { *_retval = false; return NS_OK; diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp index e74c7004a431..87af06719090 100644 --- a/netwerk/protocol/http/HttpChannelChild.cpp +++ b/netwerk/protocol/http/HttpChannelChild.cpp @@ -3678,9 +3678,8 @@ nsresult HttpChannelChild::SetReferrerHeader(const nsACString& aReferrer, } // remove old referrer if any - mClientSetRequestHeaders.RemoveElementsBy([](const auto& header) { - return NS_LITERAL_CSTRING("Referer").Equals(header.mHeader); - }); + mClientSetRequestHeaders.RemoveElementsBy( + [](const auto& header) { return "Referer"_ns.Equals(header.mHeader); }); return HttpBaseChannel::SetReferrerHeader(aReferrer, aRespectBeforeConnect); } @@ -3955,9 +3954,8 @@ HttpChannelChild::LogMimeTypeMismatch(const nsACString& aMessageName, params.AppendElement(aContentType); nsContentUtils::ReportToConsole( aWarning ? nsIScriptError::warningFlag : nsIScriptError::errorFlag, - NS_LITERAL_CSTRING("MIMEMISMATCH"), doc, - nsContentUtils::eSECURITY_PROPERTIES, nsCString(aMessageName).get(), - params); + "MIMEMISMATCH"_ns, doc, nsContentUtils::eSECURITY_PROPERTIES, + nsCString(aMessageName).get(), params); return NS_OK; } diff --git a/netwerk/protocol/http/HttpTrafficAnalyzer.cpp b/netwerk/protocol/http/HttpTrafficAnalyzer.cpp index 54eacbffbdb1..29e2ac695392 100644 --- a/netwerk/protocol/http/HttpTrafficAnalyzer.cpp +++ b/netwerk/protocol/http/HttpTrafficAnalyzer.cpp @@ -16,7 +16,7 @@ namespace net { NS_NAMED_LITERAL_CSTRING(kInvalidCategory, "INVALID_CATEGORY"); -#define DEFINE_CATEGORY(_name, _idx) NS_LITERAL_CSTRING("Y" #_idx "_" #_name), +#define DEFINE_CATEGORY(_name, _idx) nsLiteralCString("Y" #_idx "_" #_name), static const nsCString gKeyName[] = { #include "HttpTrafficAnalyzer.inc" kInvalidCategory, @@ -186,7 +186,7 @@ void HttpTrafficAnalyzer::IncrementHttpTransaction( LOG(("HttpTrafficAnalyzer::IncrementHttpTransaction [%s] [this=%p]\n", gKeyName[aCategory].get(), this)); - Telemetry::AccumulateCategoricalKeyed(NS_LITERAL_CSTRING("Transaction"), + Telemetry::AccumulateCategoricalKeyed("Transaction"_ns, gTelemetryLabel[aCategory]); } @@ -199,7 +199,7 @@ void HttpTrafficAnalyzer::IncrementHttpConnection( LOG(("HttpTrafficAnalyzer::IncrementHttpConnection [%s] [this=%p]\n", gKeyName[aCategory].get(), this)); - Telemetry::AccumulateCategoricalKeyed(NS_LITERAL_CSTRING("Connection"), + Telemetry::AccumulateCategoricalKeyed("Connection"_ns, gTelemetryLabel[aCategory]); } diff --git a/netwerk/protocol/http/InterceptedChannel.cpp b/netwerk/protocol/http/InterceptedChannel.cpp index 98e52d0937a1..51fc4ab9b89e 100644 --- a/netwerk/protocol/http/InterceptedChannel.cpp +++ b/netwerk/protocol/http/InterceptedChannel.cpp @@ -86,7 +86,7 @@ nsresult InterceptedChannelBase::DoSynthesizeHeader(const nsACString& aName, const nsACString& aValue) { EnsureSynthesizedResponse(); - nsAutoCString header = aName + NS_LITERAL_CSTRING(": ") + aValue; + nsAutoCString header = aName + ": "_ns + aValue; // Overwrite any existing header. return (*mSynthesizedResponseHead)->ParseHeaderLine(header); } @@ -154,9 +154,8 @@ InterceptedChannelBase::SaveTimeStamps() { bool isNonSubresourceRequest = nsContentUtils::IsNonSubresourceRequest(channel); - nsCString navigationOrSubresource = isNonSubresourceRequest - ? NS_LITERAL_CSTRING("navigation") - : NS_LITERAL_CSTRING("subresource"); + nsCString navigationOrSubresource = + isNonSubresourceRequest ? "navigation"_ns : "subresource"_ns; nsAutoCString subresourceKey(EmptyCString()); GetSubresourceTimeStampKey(channel, subresourceKey); diff --git a/netwerk/protocol/http/InterceptedHttpChannel.cpp b/netwerk/protocol/http/InterceptedHttpChannel.cpp index 54be9ec5f83a..af0ff9abc207 100644 --- a/netwerk/protocol/http/InterceptedHttpChannel.cpp +++ b/netwerk/protocol/http/InterceptedHttpChannel.cpp @@ -699,7 +699,7 @@ InterceptedHttpChannel::SynthesizeHeader(const nsACString& aName, mSynthesizedResponseHead.reset(new nsHttpResponseHead()); } - nsAutoCString header = aName + NS_LITERAL_CSTRING(": ") + aValue; + nsAutoCString header = aName + ": "_ns + aValue; // Overwrite any existing header. nsresult rv = mSynthesizedResponseHead->ParseHeaderLine(header); NS_ENSURE_SUCCESS(rv, rv); @@ -925,9 +925,8 @@ InterceptedHttpChannel::SaveTimeStamps(void) { } bool isNonSubresourceRequest = nsContentUtils::IsNonSubresourceRequest(this); - nsCString navigationOrSubresource = isNonSubresourceRequest - ? NS_LITERAL_CSTRING("navigation") - : NS_LITERAL_CSTRING("subresource"); + nsCString navigationOrSubresource = + isNonSubresourceRequest ? "navigation"_ns : "subresource"_ns; nsAutoCString subresourceKey(EmptyCString()); GetSubresourceTimeStampKey(this, subresourceKey); diff --git a/netwerk/protocol/http/NullHttpChannel.cpp b/netwerk/protocol/http/NullHttpChannel.cpp index 9355ddccedb9..900c48ade9b6 100644 --- a/netwerk/protocol/http/NullHttpChannel.cpp +++ b/netwerk/protocol/http/NullHttpChannel.cpp @@ -26,7 +26,7 @@ NullHttpChannel::NullHttpChannel(nsIHttpChannel* chan) nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager(); ssm->GetChannelURIPrincipal(chan, getter_AddRefs(mResourcePrincipal)); - Unused << chan->GetResponseHeader(NS_LITERAL_CSTRING("Timing-Allow-Origin"), + Unused << chan->GetResponseHeader("Timing-Allow-Origin"_ns, mTimingAllowOriginHeader); chan->GetURI(getter_AddRefs(mURI)); chan->GetOriginalURI(getter_AddRefs(mOriginalURI)); diff --git a/netwerk/protocol/http/nsCORSListenerProxy.cpp b/netwerk/protocol/http/nsCORSListenerProxy.cpp index 576ce69a7b35..e9bd79fdce33 100644 --- a/netwerk/protocol/http/nsCORSListenerProxy.cpp +++ b/netwerk/protocol/http/nsCORSListenerProxy.cpp @@ -535,8 +535,8 @@ nsresult nsCORSListenerProxy::CheckRequestApproved(nsIRequest* aRequest) { return rv; } - rv = http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Origin"), allowedOriginHeader); + rv = http->GetResponseHeader("Access-Control-Allow-Origin"_ns, + allowedOriginHeader); if (NS_FAILED(rv)) { LogBlockedRequest(aRequest, "CORSMissingAllowOrigin", nullptr, nsILoadInfo::BLOCKING_REASON_CORSMISSINGALLOWORIGIN, @@ -577,9 +577,8 @@ nsresult nsCORSListenerProxy::CheckRequestApproved(nsIRequest* aRequest) { // Check Access-Control-Allow-Credentials header if (mWithCredentials) { nsAutoCString allowCredentialsHeader; - rv = http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Credentials"), - allowCredentialsHeader); + rv = http->GetResponseHeader("Access-Control-Allow-Credentials"_ns, + allowCredentialsHeader); if (!allowCredentialsHeader.EqualsLiteral("true")) { LogBlockedRequest( @@ -1001,16 +1000,15 @@ nsresult nsCORSListenerProxy::CheckPreflightNeeded(nsIChannel* aChannel, // Add Content-Type header if needed nsTArray headers; nsAutoCString contentTypeHeader; - nsresult rv = http->GetRequestHeader(NS_LITERAL_CSTRING("Content-Type"), - contentTypeHeader); + nsresult rv = http->GetRequestHeader("Content-Type"_ns, contentTypeHeader); // GetRequestHeader return an error if the header is not set. Don't add // "content-type" to the list if that's the case. if (NS_SUCCEEDED(rv) && !nsContentUtils::IsAllowedNonCorsContentType(contentTypeHeader) && - !loadInfoHeaders.Contains(NS_LITERAL_CSTRING("content-type"), + !loadInfoHeaders.Contains("content-type"_ns, nsCaseInsensitiveCStringArrayComparator())) { headers.AppendElements(loadInfoHeaders); - headers.AppendElement(NS_LITERAL_CSTRING("content-type")); + headers.AppendElement("content-type"_ns); doPreflight = true; } @@ -1086,8 +1084,7 @@ void nsCORSPreflightListener::AddResultToCache(nsIRequest* aRequest) { // The "Access-Control-Max-Age" header should return an age in seconds. nsAutoCString headerVal; uint32_t age = 0; - Unused << http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Max-Age"), headerVal); + Unused << http->GetResponseHeader("Access-Control-Max-Age"_ns, headerVal); if (headerVal.IsEmpty()) { age = PREFLIGHT_DEFAULT_EXPIRY_SECONDS; } else { @@ -1130,8 +1127,8 @@ void nsCORSPreflightListener::AddResultToCache(nsIRequest* aRequest) { // The "Access-Control-Allow-Methods" header contains a comma separated // list of method names. - Unused << http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Methods"), headerVal); + Unused << http->GetResponseHeader("Access-Control-Allow-Methods"_ns, + headerVal); nsCCharSeparatedTokenizer methods(headerVal, ','); while (methods.hasMoreTokens()) { @@ -1159,8 +1156,8 @@ void nsCORSPreflightListener::AddResultToCache(nsIRequest* aRequest) { // The "Access-Control-Allow-Headers" header contains a comma separated // list of method names. - Unused << http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Headers"), headerVal); + Unused << http->GetResponseHeader("Access-Control-Allow-Headers"_ns, + headerVal); nsCCharSeparatedTokenizer headers(headerVal, ','); while (headers.hasMoreTokens()) { @@ -1272,8 +1269,8 @@ nsresult nsCORSPreflightListener::CheckPreflightRequestApproved( nsAutoCString headerVal; // The "Access-Control-Allow-Methods" header contains a comma separated // list of method names. - Unused << http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Methods"), headerVal); + Unused << http->GetResponseHeader("Access-Control-Allow-Methods"_ns, + headerVal); bool foundMethod = mPreflightMethod.EqualsLiteral("GET") || mPreflightMethod.EqualsLiteral("HEAD") || mPreflightMethod.EqualsLiteral("POST"); @@ -1306,8 +1303,8 @@ nsresult nsCORSPreflightListener::CheckPreflightRequestApproved( // The "Access-Control-Allow-Headers" header contains a comma separated // list of header names. - Unused << http->GetResponseHeader( - NS_LITERAL_CSTRING("Access-Control-Allow-Headers"), headerVal); + Unused << http->GetResponseHeader("Access-Control-Allow-Headers"_ns, + headerVal); nsTArray headers; nsCCharSeparatedTokenizer headerTokens(headerVal, ','); bool allowAllHeaders = false; @@ -1471,11 +1468,11 @@ nsresult nsCORSListenerProxy::StartCORSPreflight( nsCOMPtr preHttp = do_QueryInterface(preflightChannel); NS_ASSERTION(preHttp, "Failed to QI to nsIHttpChannel!"); - rv = preHttp->SetRequestMethod(NS_LITERAL_CSTRING("OPTIONS")); + rv = preHttp->SetRequestMethod("OPTIONS"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = preHttp->SetRequestHeader( - NS_LITERAL_CSTRING("Access-Control-Request-Method"), method, false); + rv = preHttp->SetRequestHeader("Access-Control-Request-Method"_ns, method, + false); NS_ENSURE_SUCCESS(rv, rv); // Set the CORS preflight channel's warning reporter to be the same as the @@ -1501,8 +1498,8 @@ nsresult nsCORSListenerProxy::StartCORSPreflight( } headers += preflightHeaders[i]; } - rv = preHttp->SetRequestHeader( - NS_LITERAL_CSTRING("Access-Control-Request-Headers"), headers, false); + rv = preHttp->SetRequestHeader("Access-Control-Request-Headers"_ns, headers, + false); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/netwerk/protocol/http/nsHttp.cpp b/netwerk/protocol/http/nsHttp.cpp index 80e4703280fe..d81bcad5af29 100644 --- a/netwerk/protocol/http/nsHttp.cpp +++ b/netwerk/protocol/http/nsHttp.cpp @@ -28,9 +28,7 @@ namespace mozilla { namespace net { const uint32_t kHttp3VersionCount = 3; -const nsCString kHttp3Versions[] = {NS_LITERAL_CSTRING("h3-27"), - NS_LITERAL_CSTRING("h3-28"), - NS_LITERAL_CSTRING("h3-29")}; +const nsCString kHttp3Versions[] = {"h3-27"_ns, "h3-28"_ns, "h3-29"_ns}; // define storage for all atoms namespace nsHttp { diff --git a/netwerk/protocol/http/nsHttpActivityDistributor.cpp b/netwerk/protocol/http/nsHttpActivityDistributor.cpp index 98f564cb72f6..a9dbf920be07 100644 --- a/netwerk/protocol/http/nsHttpActivityDistributor.cpp +++ b/netwerk/protocol/http/nsHttpActivityDistributor.cpp @@ -85,7 +85,7 @@ nsHttpActivityDistributor::ObserveActivityWithArgs( } } else if (args.type() == HttpActivityArgs::THttpActivity) { nsCOMPtr uri; - nsAutoCString portStr(NS_LITERAL_CSTRING("")); + nsAutoCString portStr(""_ns); int32_t port = args.get_HttpActivity().port(); bool endToEndSSL = args.get_HttpActivity().endToEndSSL(); if (port != -1 && @@ -94,8 +94,7 @@ nsHttpActivityDistributor::ObserveActivityWithArgs( } nsresult rv = NS_NewURI(getter_AddRefs(uri), - (endToEndSSL ? NS_LITERAL_CSTRING("https://") - : NS_LITERAL_CSTRING("http://")) + + (endToEndSSL ? "https://"_ns : "http://"_ns) + args.get_HttpActivity().host() + portStr); if (NS_FAILED(rv)) { return; diff --git a/netwerk/protocol/http/nsHttpChannel.cpp b/netwerk/protocol/http/nsHttpChannel.cpp index d8f1b24c1450..cf932fbb8a69 100644 --- a/netwerk/protocol/http/nsHttpChannel.cpp +++ b/netwerk/protocol/http/nsHttpChannel.cpp @@ -178,21 +178,20 @@ void AccumulateCacheHitTelemetry(CacheDisposition hitOrMiss, if (nsContentUtils::IsJavascriptMIMEType( NS_ConvertUTF8toUTF16(contentType))) { key.AssignLiteral("JAVASCRIPT"); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/css")) || + } else if (StringBeginsWith(contentType, "text/css"_ns) || (loadInfo && loadInfo->GetExternalContentPolicyType() == nsIContentPolicy::TYPE_STYLESHEET)) { key.AssignLiteral("STYLESHEET"); - } else if (StringBeginsWith(contentType, - NS_LITERAL_CSTRING("application/wasm"))) { + } else if (StringBeginsWith(contentType, "application/wasm"_ns)) { key.AssignLiteral("WASM"); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/"))) { + } else if (StringBeginsWith(contentType, "image/"_ns)) { key.AssignLiteral("IMAGE"); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("video/"))) { + } else if (StringBeginsWith(contentType, "video/"_ns)) { key.AssignLiteral("MEDIA"); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("audio/"))) { + } else if (StringBeginsWith(contentType, "audio/"_ns)) { key.AssignLiteral("MEDIA"); } else if (!StringBeginsWith(contentType, - NS_LITERAL_CSTRING(UNKNOWN_CONTENT_TYPE))) { + nsLiteralCString(UNKNOWN_CONTENT_TYPE))) { key.AssignLiteral("OTHER"); } } @@ -221,7 +220,7 @@ void AccumulateCacheHitTelemetry(CacheDisposition hitOrMiss, } Telemetry::AccumulateCategoricalKeyed(key, label); - Telemetry::AccumulateCategoricalKeyed(NS_LITERAL_CSTRING("ALL"), label); + Telemetry::AccumulateCategoricalKeyed("ALL"_ns, label); } // Computes and returns a SHA1 hash of the input buffer. The input buffer @@ -574,8 +573,7 @@ nsresult nsHttpChannel::OnBeforeConnect() { if (type == nsIContentPolicy::TYPE_DOCUMENT || type == nsIContentPolicy::TYPE_SUBDOCUMENT) { - rv = SetRequestHeader(NS_LITERAL_CSTRING("Upgrade-Insecure-Requests"), - NS_LITERAL_CSTRING("1"), false); + rv = SetRequestHeader("Upgrade-Insecure-Requests"_ns, "1"_ns, false); NS_ENSURE_SUCCESS(rv, rv); } @@ -1527,9 +1525,9 @@ nsresult ProcessXCTO(nsHttpChannel* aChannel, nsIURI* aURI, CopyUTF8toUTF16(contentTypeOptionsHeader, *params.AppendElement()); RefPtr doc; aLoadInfo->GetLoadingDocument(getter_AddRefs(doc)); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("XCTO"), doc, - nsContentUtils::eSECURITY_PROPERTIES, "XCTOHeaderValueMissing", params); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "XCTO"_ns, doc, + nsContentUtils::eSECURITY_PROPERTIES, + "XCTOHeaderValueMissing", params); return NS_OK; } @@ -1675,22 +1673,22 @@ nsresult EnsureMIMEOfScript(nsHttpChannel* aChannel, nsIURI* aURI, } bool block = false; - if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("image/"))) { + if (StringBeginsWith(contentType, "image/"_ns)) { // script load has type image AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::image); block = true; - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("audio/"))) { + } else if (StringBeginsWith(contentType, "audio/"_ns)) { // script load has type audio AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::audio); block = true; - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("video/"))) { + } else if (StringBeginsWith(contentType, "video/"_ns)) { // script load has type video AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::video); block = true; - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/csv"))) { + } else if (StringBeginsWith(contentType, "text/csv"_ns)) { // script load has type text/csv AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::text_csv); @@ -1708,34 +1706,31 @@ nsresult EnsureMIMEOfScript(nsHttpChannel* aChannel, nsIURI* aURI, return NS_ERROR_CORRUPTED_CONTENT; } - if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/plain"))) { + if (StringBeginsWith(contentType, "text/plain"_ns)) { // script load has type text/plain AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::text_plain); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/xml"))) { + } else if (StringBeginsWith(contentType, "text/xml"_ns)) { // script load has type text/xml AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::text_xml); - } else if (StringBeginsWith(contentType, - NS_LITERAL_CSTRING("application/octet-stream"))) { + } else if (StringBeginsWith(contentType, "application/octet-stream"_ns)) { // script load has type application/octet-stream AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::app_octet_stream); - } else if (StringBeginsWith(contentType, - NS_LITERAL_CSTRING("application/xml"))) { + } else if (StringBeginsWith(contentType, "application/xml"_ns)) { // script load has type application/xml AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::app_xml); - } else if (StringBeginsWith(contentType, - NS_LITERAL_CSTRING("application/json"))) { + } else if (StringBeginsWith(contentType, "application/json"_ns)) { // script load has type application/json AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::app_json); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/json"))) { + } else if (StringBeginsWith(contentType, "text/json"_ns)) { // script load has type text/json AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::text_json); - } else if (StringBeginsWith(contentType, NS_LITERAL_CSTRING("text/html"))) { + } else if (StringBeginsWith(contentType, "text/html"_ns)) { // script load has type text/html AccumulateCategorical( Telemetry::LABELS_SCRIPT_BLOCK_INCORRECT_MIME_3::text_html); @@ -1830,18 +1825,17 @@ void nsHttpChannel::SetCachedContentType() { if (nsContentUtils::IsJavascriptMIMEType( NS_ConvertUTF8toUTF16(contentTypeStr))) { contentType = nsICacheEntry::CONTENT_TYPE_JAVASCRIPT; - } else if (StringBeginsWith(contentTypeStr, NS_LITERAL_CSTRING("text/css")) || + } else if (StringBeginsWith(contentTypeStr, "text/css"_ns) || (mLoadInfo->GetExternalContentPolicyType() == nsIContentPolicy::TYPE_STYLESHEET)) { contentType = nsICacheEntry::CONTENT_TYPE_STYLESHEET; - } else if (StringBeginsWith(contentTypeStr, - NS_LITERAL_CSTRING("application/wasm"))) { + } else if (StringBeginsWith(contentTypeStr, "application/wasm"_ns)) { contentType = nsICacheEntry::CONTENT_TYPE_WASM; - } else if (StringBeginsWith(contentTypeStr, NS_LITERAL_CSTRING("image/"))) { + } else if (StringBeginsWith(contentTypeStr, "image/"_ns)) { contentType = nsICacheEntry::CONTENT_TYPE_IMAGE; - } else if (StringBeginsWith(contentTypeStr, NS_LITERAL_CSTRING("video/"))) { + } else if (StringBeginsWith(contentTypeStr, "video/"_ns)) { contentType = nsICacheEntry::CONTENT_TYPE_MEDIA; - } else if (StringBeginsWith(contentTypeStr, NS_LITERAL_CSTRING("audio/"))) { + } else if (StringBeginsWith(contentTypeStr, "audio/"_ns)) { contentType = nsICacheEntry::CONTENT_TYPE_MEDIA; } @@ -1960,7 +1954,7 @@ nsresult nsHttpChannel::CallOnStartRequest() { mResponseHead->SetContentType(mContentTypeHint); else if (mResponseHead->Version() == HttpVersion::v0_9 && mConnectionInfo->OriginPort() != mConnectionInfo->DefaultPort()) - mResponseHead->SetContentType(NS_LITERAL_CSTRING(TEXT_PLAIN)); + mResponseHead->SetContentType(nsLiteralCString(TEXT_PLAIN)); else { // Uh-oh. We had better find out what type we are! nsCOMPtr serv; @@ -1991,7 +1985,7 @@ nsresult nsHttpChannel::CallOnStartRequest() { nsAutoCString contentType; mResponseHead->ContentType(contentType); - if (contentType.Equals(NS_LITERAL_CSTRING("multipart/x-mixed-replace"))) { + if (contentType.Equals("multipart/x-mixed-replace"_ns)) { nsCOMPtr convServ( do_GetService("@mozilla.org/streamConverters;1", &rv)); if (NS_SUCCEEDED(rv)) { @@ -2137,31 +2131,31 @@ static void GetSTSConsoleErrorTag(uint32_t failureResult, nsAString& consoleErrorTag) { switch (failureResult) { case nsISiteSecurityService::ERROR_UNTRUSTWORTHY_CONNECTION: - consoleErrorTag = NS_LITERAL_STRING("STSUntrustworthyConnection"); + consoleErrorTag = u"STSUntrustworthyConnection"_ns; break; case nsISiteSecurityService::ERROR_COULD_NOT_PARSE_HEADER: - consoleErrorTag = NS_LITERAL_STRING("STSCouldNotParseHeader"); + consoleErrorTag = u"STSCouldNotParseHeader"_ns; break; case nsISiteSecurityService::ERROR_NO_MAX_AGE: - consoleErrorTag = NS_LITERAL_STRING("STSNoMaxAge"); + consoleErrorTag = u"STSNoMaxAge"_ns; break; case nsISiteSecurityService::ERROR_MULTIPLE_MAX_AGES: - consoleErrorTag = NS_LITERAL_STRING("STSMultipleMaxAges"); + consoleErrorTag = u"STSMultipleMaxAges"_ns; break; case nsISiteSecurityService::ERROR_INVALID_MAX_AGE: - consoleErrorTag = NS_LITERAL_STRING("STSInvalidMaxAge"); + consoleErrorTag = u"STSInvalidMaxAge"_ns; break; case nsISiteSecurityService::ERROR_MULTIPLE_INCLUDE_SUBDOMAINS: - consoleErrorTag = NS_LITERAL_STRING("STSMultipleIncludeSubdomains"); + consoleErrorTag = u"STSMultipleIncludeSubdomains"_ns; break; case nsISiteSecurityService::ERROR_INVALID_INCLUDE_SUBDOMAINS: - consoleErrorTag = NS_LITERAL_STRING("STSInvalidIncludeSubdomains"); + consoleErrorTag = u"STSInvalidIncludeSubdomains"_ns; break; case nsISiteSecurityService::ERROR_COULD_NOT_SAVE_STATE: - consoleErrorTag = NS_LITERAL_STRING("STSCouldNotSaveState"); + consoleErrorTag = u"STSCouldNotSaveState"_ns; break; default: - consoleErrorTag = NS_LITERAL_STRING("STSUnknownError"); + consoleErrorTag = u"STSUnknownError"_ns; break; } } @@ -2202,7 +2196,7 @@ nsresult nsHttpChannel::ProcessSingleSecurityHeader( switch (aType) { case nsISiteSecurityService::HEADER_HSTS: GetSTSConsoleErrorTag(failureResult, consoleErrorTag); - consoleErrorCategory = NS_LITERAL_STRING("Invalid HSTS Headers"); + consoleErrorCategory = u"Invalid HSTS Headers"_ns; break; default: return NS_ERROR_FAILURE; @@ -2338,8 +2332,8 @@ void nsHttpChannel::ProcessSSLInformation() { (state & nsIWebProgressListener::STATE_IS_BROKEN)) { // Send weak crypto warnings to the web console if (state & nsIWebProgressListener::STATE_USES_WEAK_CRYPTO) { - nsString consoleErrorTag = NS_LITERAL_STRING("WeakCipherSuiteWarning"); - nsString consoleErrorCategory = NS_LITERAL_STRING("SSL"); + nsString consoleErrorTag = u"WeakCipherSuiteWarning"_ns; + nsString consoleErrorCategory = u"SSL"_ns; Unused << AddSecurityMessage(consoleErrorTag, consoleErrorCategory); } } @@ -2360,8 +2354,8 @@ void nsHttpChannel::ProcessSSLInformation() { if (tag == SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION || tag == SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST || tag == SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE) { - nsString consoleErrorTag = NS_LITERAL_STRING("SHA1Sig"); - nsString consoleErrorMessage = NS_LITERAL_STRING("SHA-1 Signature"); + nsString consoleErrorTag = u"SHA1Sig"_ns; + nsString consoleErrorMessage = u"SHA-1 Signature"_ns; Unused << AddSecurityMessage(consoleErrorTag, consoleErrorMessage); } } @@ -2372,8 +2366,8 @@ void nsHttpChannel::ProcessSSLInformation() { if (NS_SUCCEEDED(rv) && tlsVersion != nsITransportSecurityInfo::TLS_VERSION_1_2 && tlsVersion != nsITransportSecurityInfo::TLS_VERSION_1_3) { - nsString consoleErrorTag = NS_LITERAL_STRING("DeprecatedTLSVersion2"); - nsString consoleErrorCategory = NS_LITERAL_STRING("TLS"); + nsString consoleErrorTag = u"DeprecatedTLSVersion2"_ns; + nsString consoleErrorCategory = u"TLS"_ns; Unused << AddSecurityMessage(consoleErrorTag, consoleErrorCategory); } } @@ -3498,8 +3492,7 @@ bool nsHttpChannel::IsResumable(int64_t partialLen, int64_t contentLength, nsAutoCString etag; Unused << mCachedResponseHead->GetHeader(nsHttp::ETag, etag); - bool hasWeakEtag = - !etag.IsEmpty() && StringBeginsWith(etag, NS_LITERAL_CSTRING("W/")); + bool hasWeakEtag = !etag.IsEmpty() && StringBeginsWith(etag, "W/"_ns); return (partialLen < contentLength) && (partialLen > 0 || ignoreMissingPartialLen) && !hasContentEncoding && @@ -4478,9 +4471,8 @@ nsHttpChannel::OnCacheEntryCheck(nsICacheEntry* entry, (methodWasGet || methodWasHead)) { nsAutoCString cachedETag; Unused << mCachedResponseHead->GetHeader(nsHttp::ETag, cachedETag); - if (!cachedETag.IsEmpty() && - (StringBeginsWith(cachedETag, NS_LITERAL_CSTRING("W/")) || - !requestedETag.Equals(cachedETag))) { + if (!cachedETag.IsEmpty() && (StringBeginsWith(cachedETag, "W/"_ns) || + !requestedETag.Equals(cachedETag))) { // User has defined If-Match header, if the cached entry is not // matching the provided header value or the cached ETag is weak, // force validation. @@ -5673,7 +5665,7 @@ nsresult DoAddCacheEntryHeaders(nsHttpChannel* self, nsICacheEntry* entry, // If hash failed, store a string not very likely // to be the result of subsequent hashes if (NS_FAILED(rv)) { - val = NS_LITERAL_CSTRING(""); + val = ""_ns; } else { val = hash; } @@ -6816,8 +6808,7 @@ nsresult nsHttpChannel::BeginConnect() { nsCOMPtr consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); if (consoleService) { - nsAutoString message( - NS_LITERAL_STRING("Alternate Service Mapping found: ")); + nsAutoString message(u"Alternate Service Mapping found: "_ns); AppendASCIItoUTF16(scheme, message); message.AppendLiteral(u"://"); AppendASCIItoUTF16(host, message); @@ -8016,15 +8007,15 @@ nsresult nsHttpChannel::ContinueOnStopRequest(nsresult aStatus, bool aIsFromNet, nsCString upgradeKey; if (IsHTTPS()) { // Browser upgrading is disabled and the content is already HTTPS - upgradeKey = NS_LITERAL_CSTRING("disabledNoReason"); + upgradeKey = "disabledNoReason"_ns; // Checks "security.mixed_content.upgrade_display_content" is true if (StaticPrefs::security_mixed_content_upgrade_display_content()) { if (mLoadInfo->GetBrowserUpgradeInsecureRequests()) { // HTTP content the browser has upgraded to HTTPS - upgradeKey = NS_LITERAL_CSTRING("enabledUpgrade"); + upgradeKey = "enabledUpgrade"_ns; } else { // Content wasn't upgraded but is already HTTPS - upgradeKey = NS_LITERAL_CSTRING("enabledNoReason"); + upgradeKey = "enabledNoReason"_ns; } } // shift http to https disposition enums @@ -8033,12 +8024,12 @@ nsresult nsHttpChannel::ContinueOnStopRequest(nsresult aStatus, bool aIsFromNet, } else if (mLoadInfo->GetBrowserWouldUpgradeInsecureRequests()) { // HTTP content the browser would upgrade to HTTPS if upgrading was // enabled - upgradeKey = NS_LITERAL_CSTRING("disabledUpgrade"); + upgradeKey = "disabledUpgrade"_ns; } else { // HTTP content that wouldn't upgrade upgradeKey = StaticPrefs::security_mixed_content_upgrade_display_content() - ? NS_LITERAL_CSTRING("enabledWont") - : NS_LITERAL_CSTRING("disabledWont"); + ? "enabledWont"_ns + : "disabledWont"_ns; } Telemetry::AccumulateCategoricalKeyed(upgradeKey, upgradeChanDisposition); LOG((" nsHttpChannel::OnStopRequest ChannelDisposition %d\n", @@ -8317,8 +8308,8 @@ nsHttpChannel::OnDataAvailable(nsIRequest* request, nsIInputStream* input, NS_WARNING("Listener OnDataAvailable contract violation"); nsCOMPtr consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID); - nsAutoString message(NS_LITERAL_STRING( - "http channel Listener OnDataAvailable contract violation")); + nsAutoString message(nsLiteralString( + u"http channel Listener OnDataAvailable contract violation")); if (consoleService) { consoleService->LogStringMessage(message.get()); } @@ -9570,8 +9561,7 @@ void nsHttpChannel::SetOriginHeader() { if (NS_SUCCEEDED(rv) && ReferrerInfo::ShouldSetNullOriginHeader(this, uri)) { LOG(("nsHttpChannel::SetOriginHeader null Origin by Referrer-Policy")); - rv = mRequestHead.SetHeader(nsHttp::Origin, NS_LITERAL_CSTRING("null"), - false /* merge */); + rv = mRequestHead.SetHeader(nsHttp::Origin, "null"_ns, false /* merge */); MOZ_ASSERT(NS_SUCCEEDED(rv)); } return; @@ -9620,8 +9610,8 @@ void nsHttpChannel::SetDoNotTrack() { if ((loadContext && loadContext->UseTrackingProtection()) || StaticPrefs::privacy_donottrackheader_enabled()) { - DebugOnly rv = mRequestHead.SetHeader( - nsHttp::DoNotTrack, NS_LITERAL_CSTRING("1"), false); + DebugOnly rv = + mRequestHead.SetHeader(nsHttp::DoNotTrack, "1"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } diff --git a/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp b/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp index cb89b5a56be0..2f0136cfc032 100644 --- a/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp +++ b/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp @@ -802,21 +802,19 @@ nsresult nsHttpChannelAuthProvider::GetCredentialsForChallenge( // Collect statistics on how frequently the various types of HTTP // authentication are used over SSL and non-SSL connections. if (Telemetry::CanRecordPrereleaseData()) { - if (NS_LITERAL_CSTRING("basic").LowerCaseEqualsASCII(authType)) { + if ("basic"_ns.LowerCaseEqualsASCII(authType)) { Telemetry::Accumulate( Telemetry::HTTP_AUTH_TYPE_STATS, UsingSSL() ? HTTP_AUTH_BASIC_SECURE : HTTP_AUTH_BASIC_INSECURE); - } else if (NS_LITERAL_CSTRING("digest").LowerCaseEqualsASCII( - authType)) { + } else if ("digest"_ns.LowerCaseEqualsASCII(authType)) { Telemetry::Accumulate( Telemetry::HTTP_AUTH_TYPE_STATS, UsingSSL() ? HTTP_AUTH_DIGEST_SECURE : HTTP_AUTH_DIGEST_INSECURE); - } else if (NS_LITERAL_CSTRING("ntlm").LowerCaseEqualsASCII(authType)) { + } else if ("ntlm"_ns.LowerCaseEqualsASCII(authType)) { Telemetry::Accumulate( Telemetry::HTTP_AUTH_TYPE_STATS, UsingSSL() ? HTTP_AUTH_NTLM_SECURE : HTTP_AUTH_NTLM_INSECURE); - } else if (NS_LITERAL_CSTRING("negotiate") - .LowerCaseEqualsASCII(authType)) { + } else if ("negotiate"_ns.LowerCaseEqualsASCII(authType)) { Telemetry::Accumulate(Telemetry::HTTP_AUTH_TYPE_STATS, UsingSSL() ? HTTP_AUTH_NEGOTIATE_SECURE : HTTP_AUTH_NEGOTIATE_INSECURE); diff --git a/netwerk/protocol/http/nsHttpConnection.cpp b/netwerk/protocol/http/nsHttpConnection.cpp index 1a5da58126f9..aa6d454065c9 100644 --- a/netwerk/protocol/http/nsHttpConnection.cpp +++ b/netwerk/protocol/http/nsHttpConnection.cpp @@ -926,7 +926,7 @@ nsresult nsHttpConnection::SetupNPNList(nsISSLSocketControl* ssl, // For NPN, In the case of overlap, matching priority is driven by // the order of the server's advertisement - with index 0 used when // there is no match. - protocolArray.AppendElement(NS_LITERAL_CSTRING("http/1.1")); + protocolArray.AppendElement("http/1.1"_ns); if (gHttpHandler->IsSpdyEnabled() && !(caps & NS_HTTP_DISALLOW_SPDY)) { LOG(("nsHttpConnection::SetupSSL Allow SPDY NPN selection")); @@ -1247,8 +1247,8 @@ nsresult nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction* trans, MOZ_ASSERT(responseHead, "No response head?"); if (mInSpdyTunnel) { - DebugOnly rv = responseHead->SetHeader( - nsHttp::X_Firefox_Spdy_Proxy, NS_LITERAL_CSTRING("true")); + DebugOnly rv = + responseHead->SetHeader(nsHttp::X_Firefox_Spdy_Proxy, "true"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -2237,7 +2237,7 @@ nsresult nsHttpConnection::MakeConnectString(nsAHttpTransaction* trans, MOZ_ASSERT(NS_SUCCEEDED(rv)); // CONNECT host:port HTTP/1.1 - request->SetMethod(NS_LITERAL_CSTRING("CONNECT")); + request->SetMethod("CONNECT"_ns); request->SetVersion(gHttpHandler->HttpVersion()); if (h2ws) { // HTTP/2 websocket CONNECT forms need the full request URI @@ -2253,10 +2253,9 @@ nsresult nsHttpConnection::MakeConnectString(nsAHttpTransaction* trans, MOZ_ASSERT(NS_SUCCEEDED(rv)); // a CONNECT is always persistent - rv = request->SetHeader(nsHttp::Proxy_Connection, - NS_LITERAL_CSTRING("keep-alive")); + rv = request->SetHeader(nsHttp::Proxy_Connection, "keep-alive"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = request->SetHeader(nsHttp::Connection, NS_LITERAL_CSTRING("keep-alive")); + rv = request->SetHeader(nsHttp::Connection, "keep-alive"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); // all HTTP/1.1 requests must include a Host header (even though it @@ -2279,7 +2278,7 @@ nsresult nsHttpConnection::MakeConnectString(nsAHttpTransaction* trans, // in CONNECT when not used for TLS. The protocol is stored in Upgrade. // We have to copy this header here since a new HEAD request is created // for the CONNECT. - rv = request->SetHeader(NS_LITERAL_CSTRING("ALPN"), val); + rv = request->SetHeader("ALPN"_ns, val); MOZ_ASSERT(NS_SUCCEEDED(rv)); } diff --git a/netwerk/protocol/http/nsHttpConnectionInfo.cpp b/netwerk/protocol/http/nsHttpConnectionInfo.cpp index 61176b972c86..5649cad1c839 100644 --- a/netwerk/protocol/http/nsHttpConnectionInfo.cpp +++ b/netwerk/protocol/http/nsHttpConnectionInfo.cpp @@ -446,8 +446,8 @@ nsresult nsHttpConnectionInfo::CreateWildCard(nsHttpConnectionInfo** outParam) { } RefPtr clone; - clone = new nsHttpConnectionInfo(NS_LITERAL_CSTRING("*"), 0, mNPNToken, - mUsername, mTopWindowOrigin, mProxyInfo, + clone = new nsHttpConnectionInfo("*"_ns, 0, mNPNToken, mUsername, + mTopWindowOrigin, mProxyInfo, mOriginAttributes, true, mIsHttp3); // Make sure the anonymous and private flags are transferred! clone->SetAnonymous(GetAnonymous()); diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.cpp b/netwerk/protocol/http/nsHttpConnectionMgr.cpp index 7696ea825cab..8f75176dad70 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp +++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp @@ -4129,10 +4129,10 @@ nsresult nsHttpConnectionMgr::nsHalfOpenSocket::SetupStreams( nsTArray socketTypes; const nsHttpConnectionInfo* ci = mEnt->mConnInfo; if (mIsHttp3) { - socketTypes.AppendElement(NS_LITERAL_CSTRING("quic")); + socketTypes.AppendElement("quic"_ns); } else { if (ci->FirstHopSSL()) { - socketTypes.AppendElement(NS_LITERAL_CSTRING("ssl")); + socketTypes.AppendElement("ssl"_ns); } else { const nsCString& defaultType = gHttpHandler->DefaultSocketType(); if (!defaultType.IsVoid()) { @@ -5431,11 +5431,11 @@ bool nsHttpConnectionMgr::GetConnectionData(nsTArray* aArg) { data.halfOpens.AppendElement(hSocket); } if (ent->mConnInfo->IsHttp3()) { - data.httpVersion = NS_LITERAL_CSTRING("HTTP/3"); + data.httpVersion = "HTTP/3"_ns; } else if (ent->mUsingSpdy) { - data.httpVersion = NS_LITERAL_CSTRING("HTTP/2"); + data.httpVersion = "HTTP/2"_ns; } else { - data.httpVersion = NS_LITERAL_CSTRING("HTTP <= 1.1"); + data.httpVersion = "HTTP <= 1.1"_ns; } data.ssl = ent->mConnInfo->EndToEndSSL(); aArg->AppendElement(data); diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp index 6e078db0dbb5..8e3495a899a8 100644 --- a/netwerk/protocol/http/nsHttpHandler.cpp +++ b/netwerk/protocol/http/nsHttpHandler.cpp @@ -149,8 +149,7 @@ static nsCString GetDeviceModelId() { do_GetService("@mozilla.org/system-info;1"); MOZ_ASSERT(infoService, "Could not find a system info service"); nsAutoString androidDevice; - nsresult rv = infoService->GetPropertyAsAString(NS_LITERAL_STRING("device"), - androidDevice); + nsresult rv = infoService->GetPropertyAsAString(u"device"_ns, androidDevice); if (NS_SUCCEEDED(rv)) { deviceModelId = NS_LossyConvertUTF16toASCII(androidDevice); } @@ -158,8 +157,7 @@ static nsCString GetDeviceModelId() { rv = Preferences::GetCString(UA_PREF("device_string"), deviceString); if (NS_SUCCEEDED(rv)) { deviceString.Trim(" ", true, true); - deviceString.ReplaceSubstring(NS_LITERAL_CSTRING("%DEVICEID%"), - deviceModelId); + deviceString.ReplaceSubstring("%DEVICEID%"_ns, deviceModelId); return std::move(deviceString); } return std::move(deviceModelId); @@ -357,8 +355,7 @@ void nsHttpHandler::SetFastOpenOSSupport() { nsCOMPtr infoService = do_GetService("@mozilla.org/system-info;1"); MOZ_ASSERT(infoService, "Could not find a system info service"); - rv = infoService->GetPropertyAsACString(NS_LITERAL_STRING("sdk_version"), - version); + rv = infoService->GetPropertyAsACString(u"sdk_version"_ns, version); # else char buf[SYS_INFO_BUFFER_LENGTH]; if (PR_GetSystemInfo(PR_SI_RELEASE, buf, sizeof(buf)) == PR_SUCCESS) { @@ -709,7 +706,7 @@ nsresult nsHttpHandler::AddStandardRequestHeaders( // add the "Send Hint" header if (mSafeHintEnabled || mParentalControlEnabled) { - rv = request->SetHeader(nsHttp::Prefer, NS_LITERAL_CSTRING("safe"), false, + rv = request->SetHeader(nsHttp::Prefer, "safe"_ns, false, nsHttpHeaderArray::eVarietyRequestDefault); if (NS_FAILED(rv)) return rv; } @@ -1000,8 +997,7 @@ void nsHttpHandler::InitUserAgentComponents() { # ifndef MOZ_UA_OS_AGNOSTIC // Don't add anything to mPlatform since it's // empty. nsAutoString androidVersion; - rv = infoService->GetPropertyAsAString(NS_LITERAL_STRING("release_version"), - androidVersion); + rv = infoService->GetPropertyAsAString(u"release_version"_ns, androidVersion); if (NS_SUCCEEDED(rv)) { mPlatform += " "; // If the 2nd character is a ".", we know the major version is a single @@ -1017,12 +1013,12 @@ void nsHttpHandler::InitUserAgentComponents() { # endif // Add the `Mobile` or `Tablet` or `TV` token when running on device. bool isTablet; - rv = infoService->GetPropertyAsBool(NS_LITERAL_STRING("tablet"), &isTablet); + rv = infoService->GetPropertyAsBool(u"tablet"_ns, &isTablet); if (NS_SUCCEEDED(rv) && isTablet) { mCompatDevice.AssignLiteral("Tablet"); } else { bool isTV; - rv = infoService->GetPropertyAsBool(NS_LITERAL_STRING("tv"), &isTV); + rv = infoService->GetPropertyAsBool(u"tv"_ns, &isTV); if (NS_SUCCEEDED(rv) && isTV) { mCompatDevice.AssignLiteral("TV"); } else { diff --git a/netwerk/protocol/http/nsHttpRequestHead.cpp b/netwerk/protocol/http/nsHttpRequestHead.cpp index 8a3418d5f40c..0cbed5346545 100644 --- a/netwerk/protocol/http/nsHttpRequestHead.cpp +++ b/netwerk/protocol/http/nsHttpRequestHead.cpp @@ -17,7 +17,7 @@ namespace mozilla { namespace net { nsHttpRequestHead::nsHttpRequestHead() - : mMethod(NS_LITERAL_CSTRING("GET")), + : mMethod("GET"_ns), mVersion(HttpVersion::v1_1), mParsedMethod(kMethod_Get), mHTTPS(false), diff --git a/netwerk/protocol/http/nsHttpResponseHead.cpp b/netwerk/protocol/http/nsHttpResponseHead.cpp index 5ed05f599515..5c058e8ddca2 100644 --- a/netwerk/protocol/http/nsHttpResponseHead.cpp +++ b/netwerk/protocol/http/nsHttpResponseHead.cpp @@ -246,9 +246,8 @@ void nsHttpResponseHead::Flatten(nsACString& buf, bool pruneTransients) { buf.AppendLiteral("1.0 "); } - buf.Append(nsPrintfCString("%u", unsigned(mStatus)) + - NS_LITERAL_CSTRING(" ") + mStatusText + - NS_LITERAL_CSTRING("\r\n")); + buf.Append(nsPrintfCString("%u", unsigned(mStatus)) + " "_ns + mStatusText + + "\r\n"_ns); mHeaders.Flatten(buf, false, pruneTransients); } diff --git a/netwerk/protocol/http/nsHttpTransaction.cpp b/netwerk/protocol/http/nsHttpTransaction.cpp index d8f383f49adc..56f9e97e2380 100644 --- a/netwerk/protocol/http/nsHttpTransaction.cpp +++ b/netwerk/protocol/http/nsHttpTransaction.cpp @@ -330,8 +330,7 @@ nsresult nsHttpTransaction::Init( // field unless the server is known to be HTTP/1.1 compliant. if ((requestHead->IsPost() || requestHead->IsPut()) && !requestBody && !requestHead->HasHeader(nsHttp::Transfer_Encoding)) { - rv = - requestHead->SetHeader(nsHttp::Content_Length, NS_LITERAL_CSTRING("0")); + rv = requestHead->SetHeader(nsHttp::Content_Length, "0"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -562,8 +561,7 @@ void nsHttpTransaction::OnActivated() { // of the header happens in the h2 compression code. We still have to // add the header to the request head here, though, so that devtools can // show that we sent the header. FUN! - Unused << mRequestHead->SetHeader(nsHttp::TE, - NS_LITERAL_CSTRING("Trailers")); + Unused << mRequestHead->SetHeader(nsHttp::TE, "Trailers"_ns); } mActivated = true; @@ -1405,8 +1403,8 @@ nsresult nsHttpTransaction::Restart() { mConnInfo->CloneAsDirectRoute(getter_AddRefs(ci)); mConnInfo = ci; if (mRequestHead) { - DebugOnly rv = mRequestHead->SetHeader( - nsHttp::Alternate_Service_Used, NS_LITERAL_CSTRING("0")); + DebugOnly rv = + mRequestHead->SetHeader(nsHttp::Alternate_Service_Used, "0"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -1688,27 +1686,26 @@ nsresult nsHttpTransaction::HandleContentStart() { mEarlyDataDisposition = EARLY_425; } else { Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_Early_Data, - NS_LITERAL_CSTRING("accepted")); + "accepted"_ns); } } else if (mEarlyDataDisposition == EARLY_SENT) { Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_Early_Data, - NS_LITERAL_CSTRING("sent")); + "sent"_ns); } else if (mEarlyDataDisposition == EARLY_425) { Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_Early_Data, - NS_LITERAL_CSTRING("received 425")); + "received 425"_ns); mEarlyDataDisposition = EARLY_NONE; } // no header on NONE case if (mFastOpenStatus == TFO_DATA_SENT) { Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_TCP_Fast_Open, - NS_LITERAL_CSTRING("data sent")); + "data sent"_ns); } else if (mFastOpenStatus == TFO_TRIED) { - Unused << mResponseHead->SetHeader( - nsHttp::X_Firefox_TCP_Fast_Open, - NS_LITERAL_CSTRING("tried negotiating")); + Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_TCP_Fast_Open, + "tried negotiating"_ns); } else if (mFastOpenStatus == TFO_FAILED) { Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_TCP_Fast_Open, - NS_LITERAL_CSTRING("failed")); + "failed"_ns); } // no header on TFO_NOT_TRIED case if (LOG3_ENABLED()) { diff --git a/netwerk/protocol/res/ExtensionProtocolHandler.cpp b/netwerk/protocol/res/ExtensionProtocolHandler.cpp index 44c02d6594fb..9fd73336070e 100644 --- a/netwerk/protocol/res/ExtensionProtocolHandler.cpp +++ b/netwerk/protocol/res/ExtensionProtocolHandler.cpp @@ -828,9 +828,8 @@ Result ExtensionProtocolHandler::NewFD( MOZ_TRY(innerFileURL->GetFile(getter_AddRefs(jarFile))); if (!mFileOpenerThread) { - mFileOpenerThread = - new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, - NS_LITERAL_CSTRING("ExtensionProtocolHandler")); + mFileOpenerThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, + "ExtensionProtocolHandler"_ns); } RefPtr fileOpener = diff --git a/netwerk/protocol/res/PageThumbProtocolHandler.cpp b/netwerk/protocol/res/PageThumbProtocolHandler.cpp index b3e6c3004888..e4b9cdc0e8ce 100644 --- a/netwerk/protocol/res/PageThumbProtocolHandler.cpp +++ b/netwerk/protocol/res/PageThumbProtocolHandler.cpp @@ -414,8 +414,8 @@ nsresult PageThumbProtocolHandler::GetThumbnailPath(const nsACString& aPath, // Extract URL from query string. nsAutoString url; - bool found = dom::URLParams::Extract(Substring(aPath, queryIndex + 1), - NS_LITERAL_STRING("url"), url); + bool found = + dom::URLParams::Extract(Substring(aPath, queryIndex + 1), u"url"_ns, url); if (!found || url.IsVoid()) { return NS_ERROR_NOT_AVAILABLE; } diff --git a/netwerk/protocol/res/SubstitutingProtocolHandler.cpp b/netwerk/protocol/res/SubstitutingProtocolHandler.cpp index b0dfe4862e50..ec7e865746fd 100644 --- a/netwerk/protocol/res/SubstitutingProtocolHandler.cpp +++ b/netwerk/protocol/res/SubstitutingProtocolHandler.cpp @@ -617,8 +617,7 @@ nsresult SubstitutingProtocolHandler::ResolveURI(nsIURI* uri, if (baseDir) { nsAutoCString basePath; rv = baseURI->GetFilePath(basePath); - if (NS_SUCCEEDED(rv) && - !StringEndsWith(basePath, NS_LITERAL_CSTRING("/"))) { + if (NS_SUCCEEDED(rv) && !StringEndsWith(basePath, "/"_ns)) { // Cf. the assertion above, path already starts with a /, so prefixing // with a string that doesn't end with one will leave us wit the right // amount of /. diff --git a/netwerk/protocol/res/nsResProtocolHandler.cpp b/netwerk/protocol/res/nsResProtocolHandler.cpp index 6542b219b6ad..6918799e3591 100644 --- a/netwerk/protocol/res/nsResProtocolHandler.cpp +++ b/netwerk/protocol/res/nsResProtocolHandler.cpp @@ -75,7 +75,7 @@ nsresult nsResProtocolHandler::GetApkURI(nsACString& aResult) { nsCString::const_iterator start_iter = start; // This is like jar:jar:file://path/to/apk/base.apk!/path/to/omni.ja!/ - bool found = FindInReadable(NS_LITERAL_CSTRING("!/"), start_iter, iter); + bool found = FindInReadable("!/"_ns, start_iter, iter); NS_ENSURE_TRUE(found, NS_ERROR_UNEXPECTED); // like jar:jar:file://path/to/apk/base.apk!/ @@ -127,8 +127,7 @@ nsresult nsResProtocolHandler::GetSubstitutionInternal(const nsACString& aRoot, uint32_t* aFlags) { nsAutoCString uri; - if (!ResolveSpecialCases(aRoot, NS_LITERAL_CSTRING("/"), - NS_LITERAL_CSTRING("/"), uri)) { + if (!ResolveSpecialCases(aRoot, "/"_ns, "/"_ns, uri)) { return NS_ERROR_NOT_AVAILABLE; } diff --git a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp index 065d6d6d7f99..068223e2c867 100644 --- a/netwerk/protocol/viewsource/nsViewSourceChannel.cpp +++ b/netwerk/protocol/viewsource/nsViewSourceChannel.cpp @@ -98,13 +98,12 @@ nsresult nsViewSourceChannel::InitSrcdoc(nsIURI* aURI, nsIURI* aBaseURI, // Need to strip view-source: from the URI. Hardcoded to // about:srcdoc as this is the only permissible URI for srcdoc // loads - rv = - NS_NewURI(getter_AddRefs(inStreamURI), NS_LITERAL_STRING("about:srcdoc")); + rv = NS_NewURI(getter_AddRefs(inStreamURI), u"about:srcdoc"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = NS_NewInputStreamChannelInternal( - getter_AddRefs(mChannel), inStreamURI, aSrcdoc, - NS_LITERAL_CSTRING("text/html"), aLoadInfo, true); + rv = NS_NewInputStreamChannelInternal(getter_AddRefs(mChannel), inStreamURI, + aSrcdoc, "text/html"_ns, aLoadInfo, + true); NS_ENSURE_SUCCESS(rv, rv); mOriginalURI = aURI; @@ -188,7 +187,7 @@ nsresult nsViewSourceChannel::BuildViewSourceURI(nsIURI* aURI, return rv; } - return NS_NewURI(aResult, NS_LITERAL_CSTRING("view-source:") + spec); + return NS_NewURI(aResult, "view-source:"_ns + spec); } //////////////////////////////////////////////////////////////////////////////// @@ -896,13 +895,12 @@ nsViewSourceChannel::GetResponseHeader(const nsACString& aHeader, aValue.Truncate(); if (!mHttpChannel) return NS_ERROR_NULL_POINTER; - if (!aHeader.Equals(NS_LITERAL_CSTRING("Content-Type"), + if (!aHeader.Equals("Content-Type"_ns, nsCaseInsensitiveCStringComparator) && + !aHeader.Equals("Content-Security-Policy"_ns, nsCaseInsensitiveCStringComparator) && - !aHeader.Equals(NS_LITERAL_CSTRING("Content-Security-Policy"), + !aHeader.Equals("Content-Security-Policy-Report-Only"_ns, nsCaseInsensitiveCStringComparator) && - !aHeader.Equals(NS_LITERAL_CSTRING("Content-Security-Policy-Report-Only"), - nsCaseInsensitiveCStringComparator) && - !aHeader.Equals(NS_LITERAL_CSTRING("X-Frame-Options"), + !aHeader.Equals("X-Frame-Options"_ns, nsCaseInsensitiveCStringComparator)) { // We simulate the NS_ERROR_NOT_AVAILABLE error which is produced by // GetResponseHeader via nsHttpHeaderArray::GetHeader when the entry is diff --git a/netwerk/protocol/websocket/WebSocketChannel.cpp b/netwerk/protocol/websocket/WebSocketChannel.cpp index 1b228e917f4c..34ee34d5971e 100644 --- a/netwerk/protocol/websocket/WebSocketChannel.cpp +++ b/netwerk/protocol/websocket/WebSocketChannel.cpp @@ -2557,8 +2557,8 @@ nsresult WebSocketChannel::HandleExtensions() { MOZ_ASSERT(NS_IsMainThread(), "not main thread"); - rv = mHttpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Extensions"), extensions); + rv = mHttpChannel->GetResponseHeader("Sec-WebSocket-Extensions"_ns, + extensions); extensions.CompressWhitespace(); if (extensions.IsEmpty()) { return NS_OK; @@ -2673,8 +2673,7 @@ void ProcessServerWebSocketExtensions(const nsACString& aExtensions, nsresult CalculateWebSocketHashedSecret(const nsACString& aKey, nsACString& aHash) { nsresult rv; - nsCString key = - aKey + NS_LITERAL_CSTRING("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); + nsCString key = aKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"_ns; nsCOMPtr hasher = do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); @@ -2710,30 +2709,28 @@ nsresult WebSocketChannel::SetupRequest() { // draft-ietf-hybi-thewebsocketprotocol-07 illustrates Upgrade: websocket // in lower case, so go with that. It is technically case insensitive. - rv = mChannel->HTTPUpgrade(NS_LITERAL_CSTRING("websocket"), this); + rv = mChannel->HTTPUpgrade("websocket"_ns, this); NS_ENSURE_SUCCESS(rv, rv); - rv = mHttpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Version"), - NS_LITERAL_CSTRING(SEC_WEBSOCKET_VERSION), false); + rv = mHttpChannel->SetRequestHeader("Sec-WebSocket-Version"_ns, + nsLiteralCString(SEC_WEBSOCKET_VERSION), + false); MOZ_ASSERT(NS_SUCCEEDED(rv)); if (!mOrigin.IsEmpty()) { - rv = mHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Origin"), mOrigin, - false); + rv = mHttpChannel->SetRequestHeader("Origin"_ns, mOrigin, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } if (!mProtocol.IsEmpty()) { - rv = mHttpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Protocol"), mProtocol, true); + rv = mHttpChannel->SetRequestHeader("Sec-WebSocket-Protocol"_ns, mProtocol, + true); MOZ_ASSERT(NS_SUCCEEDED(rv)); } if (mAllowPMCE) { - rv = mHttpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Extensions"), - NS_LITERAL_CSTRING("permessage-deflate"), false); + rv = mHttpChannel->SetRequestHeader("Sec-WebSocket-Extensions"_ns, + "permessage-deflate"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -2748,8 +2745,8 @@ nsresult WebSocketChannel::SetupRequest() { return rv; } - rv = mHttpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Sec-WebSocket-Key"), - secKeyString, false); + rv = mHttpChannel->SetRequestHeader("Sec-WebSocket-Key"_ns, secKeyString, + false); MOZ_ASSERT(NS_SUCCEEDED(rv)); LOG(("WebSocketChannel::SetupRequest: client key %s\n", secKeyString.get())); @@ -3094,8 +3091,7 @@ WebSocketChannel::AsyncOnChannelRedirect( mEncrypted = newuriIsHttps; rv = NS_MutateURI(newuri) - .SetScheme(mEncrypted ? NS_LITERAL_CSTRING("wss") - : NS_LITERAL_CSTRING("ws")) + .SetScheme(mEncrypted ? "wss"_ns : "ws"_ns) .Finalize(mURI); if (NS_FAILED(rv)) { @@ -3345,8 +3341,7 @@ WebSocketChannel::AsyncOpen(nsIURI* aURI, const nsACString& aOrigin, nsCOMPtr localChannel; rv = NS_MutateURI(mURI) - .SetScheme(mEncrypted ? NS_LITERAL_CSTRING("https") - : NS_LITERAL_CSTRING("http")) + .SetScheme(mEncrypted ? "https"_ns : "http"_ns) .Finalize(localURI); NS_ENSURE_SUCCESS(rv, rv); @@ -3710,8 +3705,7 @@ WebSocketChannel::OnStartRequest(nsIRequest* aRequest) { if (versionMajor == 1) { // These are only present on http/1.x websocket upgrades nsAutoCString respUpgrade; - rv = mHttpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Upgrade"), - respUpgrade); + rv = mHttpChannel->GetResponseHeader("Upgrade"_ns, respUpgrade); if (NS_SUCCEEDED(rv)) { rv = NS_ERROR_ILLEGAL_VALUE; @@ -3735,8 +3729,7 @@ WebSocketChannel::OnStartRequest(nsIRequest* aRequest) { } nsAutoCString respConnection; - rv = mHttpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Connection"), - respConnection); + rv = mHttpChannel->GetResponseHeader("Connection"_ns, respConnection); if (NS_SUCCEEDED(rv)) { rv = NS_ERROR_ILLEGAL_VALUE; @@ -3760,8 +3753,7 @@ WebSocketChannel::OnStartRequest(nsIRequest* aRequest) { } nsAutoCString respAccept; - rv = mHttpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Accept"), respAccept); + rv = mHttpChannel->GetResponseHeader("Sec-WebSocket-Accept"_ns, respAccept); if (NS_FAILED(rv) || respAccept.IsEmpty() || !respAccept.Equals(mHashedSecret)) { @@ -3787,8 +3779,8 @@ WebSocketChannel::OnStartRequest(nsIRequest* aRequest) { // attribute of the WebSocket JS object reflects that if (!mProtocol.IsEmpty()) { nsAutoCString respProtocol; - rv = mHttpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Sec-WebSocket-Protocol"), respProtocol); + rv = mHttpChannel->GetResponseHeader("Sec-WebSocket-Protocol"_ns, + respProtocol); if (NS_SUCCEEDED(rv)) { rv = NS_ERROR_ILLEGAL_VALUE; val = mProtocol.BeginWriting(); diff --git a/netwerk/protocol/websocket/WebSocketChannelParent.cpp b/netwerk/protocol/websocket/WebSocketChannelParent.cpp index a1ab7246a994..f95c37905768 100644 --- a/netwerk/protocol/websocket/WebSocketChannelParent.cpp +++ b/netwerk/protocol/websocket/WebSocketChannelParent.cpp @@ -263,7 +263,7 @@ void WebSocketChannelParent::ActorDestroy(ActorDestroyReason why) { // through a clean shutdown. if (mChannel) { Unused << mChannel->Close(nsIWebSocketChannel::CLOSE_GOING_AWAY, - NS_LITERAL_CSTRING("Child was killed")); + "Child was killed"_ns); } } diff --git a/netwerk/sctp/datachannel/DataChannel.cpp b/netwerk/sctp/datachannel/DataChannel.cpp index 199aaa7dc09d..504b410b3a03 100644 --- a/netwerk/sctp/datachannel/DataChannel.cpp +++ b/netwerk/sctp/datachannel/DataChannel.cpp @@ -679,7 +679,7 @@ void DataChannelConnection::AppendStatsToReport( continue; } mozilla::dom::RTCDataChannelStats stats; - nsString id = NS_LITERAL_STRING("dc"); + nsString id = u"dc"_ns; id.AppendInt(chan->GetStream()); stats.mId.Construct(id); chan->GetLabel(temp); diff --git a/netwerk/socket/nsNamedPipeIOLayer.cpp b/netwerk/socket/nsNamedPipeIOLayer.cpp index f56541bb5606..3fb31a3a45e0 100644 --- a/netwerk/socket/nsNamedPipeIOLayer.cpp +++ b/netwerk/socket/nsNamedPipeIOLayer.cpp @@ -840,7 +840,7 @@ static void Initialize() { } bool IsNamedPipePath(const nsACString& aPath) { - return StringBeginsWith(aPath, NS_LITERAL_CSTRING("\\\\.\\pipe\\")); + return StringBeginsWith(aPath, "\\\\.\\pipe\\"_ns); } PRFileDesc* CreateNamedPipeLayer() { diff --git a/netwerk/socket/nsSOCKSIOLayer.cpp b/netwerk/socket/nsSOCKSIOLayer.cpp index 8556238f8b19..4bf998411f03 100644 --- a/netwerk/socket/nsSOCKSIOLayer.cpp +++ b/netwerk/socket/nsSOCKSIOLayer.cpp @@ -1515,7 +1515,7 @@ nsresult nsSOCKSIOLayerAddToSocket(int32_t family, const char* host, bool IsHostLocalTarget(const nsACString& aHost) { #if defined(XP_UNIX) - return StringBeginsWith(aHost, NS_LITERAL_CSTRING("file:")); + return StringBeginsWith(aHost, "file:"_ns); #elif defined(XP_WIN) return IsNamedPipePath(aHost); #else diff --git a/netwerk/socket/nsSOCKSSocketProvider.cpp b/netwerk/socket/nsSOCKSSocketProvider.cpp index c9ee81e624ad..536e06c96211 100644 --- a/netwerk/socket/nsSOCKSSocketProvider.cpp +++ b/netwerk/socket/nsSOCKSSocketProvider.cpp @@ -71,7 +71,7 @@ static PRFileDesc* OpenTCPSocket(int32_t family, nsIProxyInfo* proxy) { static PRFileDesc* OpenTCPSocket(int32_t family, nsIProxyInfo* proxy) { nsAutoCString proxyHost; proxy->GetHost(proxyHost); - if (StringBeginsWith(proxyHost, NS_LITERAL_CSTRING("file://"))) { + if (StringBeginsWith(proxyHost, "file://"_ns)) { family = AF_LOCAL; } diff --git a/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp b/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp index c4538f9ae5fa..1ab51adb827b 100644 --- a/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp +++ b/netwerk/streamconv/converters/mozTXTToHTMLConv.cpp @@ -932,7 +932,7 @@ int32_t mozTXTToHTMLConv::CiteLevelTXT(const char16_t* line, // here, |logLineStart < lineLength| is always true uint32_t minlength = std::min(uint32_t(6), NS_strlen(indexString)); if (Substring(indexString, indexString + minlength) - .Equals(Substring(NS_LITERAL_STRING(">From "), 0, minlength), + .Equals(Substring(u">From "_ns, 0, minlength), nsCaseInsensitiveStringComparator)) // XXX RFC2646 moreCites = false; diff --git a/netwerk/streamconv/converters/nsIndexedToHTML.cpp b/netwerk/streamconv/converters/nsIndexedToHTML.cpp index 99a1fe95c86c..d20f7b0b641d 100644 --- a/netwerk/streamconv/converters/nsIndexedToHTML.cpp +++ b/netwerk/streamconv/converters/nsIndexedToHTML.cpp @@ -135,7 +135,7 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, if (NS_FAILED(rv)) return rv; } - channel->SetContentType(NS_LITERAL_CSTRING("text/html")); + channel->SetContentType("text/html"_ns); mParser = nsDirIndexParser::CreateInstance(); if (!mParser) return NS_ERROR_FAILURE; @@ -192,7 +192,7 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, if (NS_FAILED(rv)) return rv; if (!path.EqualsLiteral("//") && !path.LowerCaseEqualsLiteral("/%2f")) { - rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr); + rv = uri->Resolve(".."_ns, parentStr); if (NS_FAILED(rv)) return rv; } } else if (uri->SchemeIs("file")) { @@ -229,8 +229,8 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, // XXX this won't work correctly when the name of the directory being // XXX displayed ends with "!", but then again, jar: URIs don't deal // XXX particularly well with such directories anyway - if (!StringEndsWith(path, NS_LITERAL_CSTRING("!/"))) { - rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr); + if (!StringEndsWith(path, "!/"_ns)) { + rv = uri->Resolve(".."_ns, parentStr); if (NS_FAILED(rv)) return rv; } } else { @@ -245,7 +245,7 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, mozilla::Unused << NS_MutateURI(uri).SetPathQueryRef(path).Finalize(uri); } if (!path.EqualsLiteral("/")) { - rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr); + rv = uri->Resolve(".."_ns, parentStr); if (NS_FAILED(rv)) return rv; } } @@ -503,8 +503,7 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, } nsAutoString unEscapeSpec; - rv = mTextToSubURI->UnEscapeAndConvert(NS_LITERAL_CSTRING("UTF-8"), titleUri, - unEscapeSpec); + rv = mTextToSubURI->UnEscapeAndConvert("UTF-8"_ns, titleUri, unEscapeSpec); if (NS_FAILED(rv)) { return rv; } @@ -547,7 +546,7 @@ nsresult nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, NS_ERROR("broken protocol handler didn't escape double-quote."); } - nsCString direction(NS_LITERAL_CSTRING("ltr")); + nsCString direction("ltr"_ns); if (LocaleService::GetInstance()->IsAppLocaleRTL()) { direction.AssignLiteral("rtl"); } diff --git a/netwerk/streamconv/converters/nsMultiMixedConv.cpp b/netwerk/streamconv/converters/nsMultiMixedConv.cpp index 42c48dd3715a..f1ebda12f2ae 100644 --- a/netwerk/streamconv/converters/nsMultiMixedConv.cpp +++ b/netwerk/streamconv/converters/nsMultiMixedConv.cpp @@ -445,14 +445,12 @@ nsMultiMixedConv::OnStartRequest(nsIRequest* request) { // ask the HTTP channel for the content-type and extract the boundary from it. nsCOMPtr httpChannel = do_QueryInterface(mChannel, &rv); if (NS_SUCCEEDED(rv)) { - rv = httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("content-type"), - contentType); + rv = httpChannel->GetResponseHeader("content-type"_ns, contentType); if (NS_FAILED(rv)) { return rv; } nsCString csp; - rv = httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("content-security-policy"), csp); + rv = httpChannel->GetResponseHeader("content-security-policy"_ns, csp); if (NS_SUCCEEDED(rv)) { mRootContentSecurityPolicy = csp; } @@ -508,8 +506,8 @@ nsMultiMixedConv::OnStartRequest(nsIRequest* request) { mBoundaryToken = mTokenizer.AddCustomToken(mBoundary, mTokenizer.CASE_SENSITIVE); - mBoundaryTokenWithDashes = mTokenizer.AddCustomToken( - NS_LITERAL_CSTRING("--") + mBoundary, mTokenizer.CASE_SENSITIVE); + mBoundaryTokenWithDashes = + mTokenizer.AddCustomToken("--"_ns + mBoundary, mTokenizer.CASE_SENSITIVE); return NS_OK; } @@ -1020,7 +1018,7 @@ nsresult nsMultiMixedConv::ProcessHeader() { resultCSP.Append(mContentSecurityPolicy); } nsresult rv = httpChannel->SetResponseHeader( - NS_LITERAL_CSTRING("Content-Security-Policy"), resultCSP, false); + "Content-Security-Policy"_ns, resultCSP, false); if (NS_FAILED(rv)) { return NS_ERROR_CORRUPTED_CONTENT; } diff --git a/netwerk/streamconv/converters/nsUnknownDecoder.cpp b/netwerk/streamconv/converters/nsUnknownDecoder.cpp index 09635810c81f..aa233fbfa019 100644 --- a/netwerk/streamconv/converters/nsUnknownDecoder.cpp +++ b/netwerk/streamconv/converters/nsUnknownDecoder.cpp @@ -437,8 +437,7 @@ void nsUnknownDecoder::DetermineContentType(nsIRequest* aRequest) { spec.AppendLiteral("..."); } httpChannel->LogMimeTypeMismatch( - NS_LITERAL_CSTRING("XTCOWithMIMEValueMissing"), false, - NS_ConvertUTF8toUTF16(spec), + "XTCOWithMIMEValueMissing"_ns, false, NS_ConvertUTF8toUTF16(spec), // Type is not used in the Error Message but required NS_ConvertUTF8toUTF16(type)); } @@ -885,8 +884,7 @@ void nsBinaryDetector::DetermineContentType(nsIRequest* aRequest) { } // It's an HTTP channel. Check for the text/plain mess nsAutoCString contentTypeHdr; - Unused << httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Content-Type"), - contentTypeHdr); + Unused << httpChannel->GetResponseHeader("Content-Type"_ns, contentTypeHdr); nsAutoCString contentType; httpChannel->GetContentType(contentType); @@ -910,8 +908,8 @@ void nsBinaryDetector::DetermineContentType(nsIRequest* aRequest) { // XXXbz we could improve this by doing a local decompress if we // wanted, I'm sure. nsAutoCString contentEncoding; - Unused << httpChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Content-Encoding"), contentEncoding); + Unused << httpChannel->GetResponseHeader("Content-Encoding"_ns, + contentEncoding); if (!contentEncoding.IsEmpty()) { return; } diff --git a/netwerk/system/netlink/NetlinkService.cpp b/netwerk/system/netlink/NetlinkService.cpp index ebe0570c560e..390c883e61f8 100644 --- a/netwerk/system/netlink/NetlinkService.cpp +++ b/netwerk/system/netlink/NetlinkService.cpp @@ -1622,7 +1622,7 @@ bool NetlinkService::CalculateIDForFamily(uint8_t aFamily, SHA1Sum* aSHA1) { if (linkInfo->mIsUp) { nsAutoCString linkName; linkInfo->mLink->GetName(linkName); - if (StringBeginsWith(linkName, NS_LITERAL_CSTRING("rmnet"))) { + if (StringBeginsWith(linkName, "rmnet"_ns)) { // Check whether there is some non-local address associated with this // link. for (uint32_t i = 0; i < linkInfo->mAddresses.Length(); ++i) { diff --git a/netwerk/system/win32/nsNotifyAddrListener.cpp b/netwerk/system/win32/nsNotifyAddrListener.cpp index 7a41e19c71ae..c2f4964e4a85 100644 --- a/netwerk/system/win32/nsNotifyAddrListener.cpp +++ b/netwerk/system/win32/nsNotifyAddrListener.cpp @@ -332,7 +332,7 @@ nsresult nsNotifyAddrListener::Init(void) { MOZ_ALWAYS_SUCCEEDS(threadPool->SetThreadLimit(1)); MOZ_ALWAYS_SUCCEEDS( threadPool->SetThreadStackSize(nsIThreadManager::kThreadPoolStackSize)); - MOZ_ALWAYS_SUCCEEDS(threadPool->SetName(NS_LITERAL_CSTRING("Link Monitor"))); + MOZ_ALWAYS_SUCCEEDS(threadPool->SetName("Link Monitor"_ns)); mThread = threadPool.forget(); return mThread->Dispatch(this, NS_DISPATCH_NORMAL); @@ -523,8 +523,7 @@ nsNotifyAddrListener::CheckAdaptersAddresses(void) { return false; } nsAutoString wideSuffixString; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("SearchList"), - wideSuffixString); + rv = regKey->ReadStringValue(u"SearchList"_ns, wideSuffixString); if (NS_FAILED(rv)) { LOG((" reading registry string value failed\n")); return false; @@ -548,10 +547,10 @@ nsNotifyAddrListener::CheckAdaptersAddresses(void) { // The Local group policy overrides the user set suffix list, so we must // first check the registry key that is sets by gpedit, and if that fails we // fall back to the one that is set by the user. - if (!checkRegistry(NS_LITERAL_STRING( - "SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient"))) { - checkRegistry(NS_LITERAL_STRING( - "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters")); + if (!checkRegistry(nsLiteralString( + u"SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient"))) { + checkRegistry(nsLiteralString( + u"SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters")); } } @@ -580,23 +579,19 @@ nsNotifyAddrListener::CheckAdaptersAddresses(void) { }; if (StaticPrefs::network_notify_checkForProxies()) { - if (registryChildCount( - NS_LITERAL_STRING("SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" - "Parameters\\DnsConnections")) > 0 || - registryChildCount( - NS_LITERAL_STRING("SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" - "Parameters\\DnsConnectionsProxies")) > 0) { + if (registryChildCount(u"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" + "Parameters\\DnsConnections"_ns) > 0 || + registryChildCount(u"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" + "Parameters\\DnsConnectionsProxies"_ns) > 0) { platformDNSIndications |= PROXY_DETECTED; } } if (StaticPrefs::network_notify_checkForNRPT()) { - if (registryChildCount( - NS_LITERAL_STRING("SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" - "Parameters\\DnsPolicyConfig")) > 0 || - registryChildCount( - NS_LITERAL_STRING("SOFTWARE\\Policies\\Microsoft\\Windows NT\\" - "DNSClient\\DnsPolicyConfig")) > 0) { + if (registryChildCount(u"SYSTEM\\CurrentControlSet\\Services\\Dnscache\\" + "Parameters\\DnsPolicyConfig"_ns) > 0 || + registryChildCount(u"SOFTWARE\\Policies\\Microsoft\\Windows NT\\" + "DNSClient\\DnsPolicyConfig"_ns) > 0) { platformDNSIndications |= NRPT_DETECTED; } } diff --git a/netwerk/test/fuzz/TestHttpFuzzing.cpp b/netwerk/test/fuzz/TestHttpFuzzing.cpp index 54278df11d43..6c26f5b7c832 100644 --- a/netwerk/test/fuzz/TestHttpFuzzing.cpp +++ b/netwerk/test/fuzz/TestHttpFuzzing.cpp @@ -190,7 +190,7 @@ static int FuzzingRunNetworkHttp(const uint8_t* data, size_t size) { nsCOMPtr gHttpChannel; gHttpChannel = do_QueryInterface(channel); - rv = gHttpChannel->SetRequestMethod(NS_LITERAL_CSTRING("GET")); + rv = gHttpChannel->SetRequestMethod("GET"_ns); if (NS_FAILED(rv)) { MOZ_CRASH("SetRequestMethod on gHttpChannel failed."); } diff --git a/netwerk/test/fuzz/TestWebsocketFuzzing.cpp b/netwerk/test/fuzz/TestWebsocketFuzzing.cpp index a02d1d7a1196..d9d76021a1b5 100644 --- a/netwerk/test/fuzz/TestWebsocketFuzzing.cpp +++ b/netwerk/test/fuzz/TestWebsocketFuzzing.cpp @@ -167,8 +167,7 @@ static int FuzzingRunNetworkWebsocket(const uint8_t* data, size_t size) { gWebSocketListener->waitUntilDoneOrStarted(); if (gWebSocketListener->isStarted()) { - rv = - gWebSocketChannel->SendBinaryMsg(NS_LITERAL_CSTRING("Hello world")); + rv = gWebSocketChannel->SendBinaryMsg("Hello world"_ns); if (rv != NS_OK) { FUZZING_LOG(("Warning: Failed to call SendBinaryMsg")); @@ -176,7 +175,7 @@ static int FuzzingRunNetworkWebsocket(const uint8_t* data, size_t size) { gWebSocketListener->waitUntilDoneOrAck(); } - rv = gWebSocketChannel->Close(1000, NS_LITERAL_CSTRING("")); + rv = gWebSocketChannel->Close(1000, ""_ns); if (rv != NS_OK) { FUZZING_LOG(("Warning: Failed to call close")); diff --git a/netwerk/test/gtest/TestBind.cpp b/netwerk/test/gtest/TestBind.cpp index 2f03a358d256..e9ee9a7153fc 100644 --- a/netwerk/test/gtest/TestBind.cpp +++ b/netwerk/test/gtest/TestBind.cpp @@ -130,8 +130,7 @@ TEST(TestBind, MainTest) for (int32_t tried = 0; tried < 100; tried++) { nsCOMPtr client; - rv = sts->CreateTransport(nsTArray(), - NS_LITERAL_CSTRING("127.0.0.1"), serverPort, + rv = sts->CreateTransport(nsTArray(), "127.0.0.1"_ns, serverPort, nullptr, getter_AddRefs(client)); ASSERT_TRUE(NS_SUCCEEDED(rv)); diff --git a/netwerk/test/gtest/TestCookie.cpp b/netwerk/test/gtest/TestCookie.cpp index 102866d5de33..d765886758af 100644 --- a/netwerk/test/gtest/TestCookie.cpp +++ b/netwerk/test/gtest/TestCookie.cpp @@ -755,39 +755,39 @@ TEST(TestCookie, TestCookieMain) // first, ensure a clean slate EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveAll())); // add some cookies + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative("cookiemgr.test"_ns, // domain + "/foo"_ns, // path + "test1"_ns, // name + "yes"_ns, // value + false, // is secure + false, // is httponly + true, // is session + INT64_MAX, // expiry time + &attrs, // originAttributes + nsICookie::SAMESITE_NONE, + nsICookie::SCHEME_HTTPS))); EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative( - NS_LITERAL_CSTRING("cookiemgr.test"), // domain - NS_LITERAL_CSTRING("/foo"), // path - NS_LITERAL_CSTRING("test1"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - false, // is httponly - true, // is session - INT64_MAX, // expiry time - &attrs, // originAttributes - nsICookie::SAMESITE_NONE, nsICookie::SCHEME_HTTPS))); - EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative( - NS_LITERAL_CSTRING("cookiemgr.test"), // domain - NS_LITERAL_CSTRING("/foo"), // path - NS_LITERAL_CSTRING("test2"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - true, // is httponly - true, // is session - PR_Now() / PR_USEC_PER_SEC + 2, // expiry time - &attrs, // originAttributes - nsICookie::SAMESITE_NONE, nsICookie::SCHEME_HTTPS))); - EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative( - NS_LITERAL_CSTRING("new.domain"), // domain - NS_LITERAL_CSTRING("/rabbit"), // path - NS_LITERAL_CSTRING("test3"), // name - NS_LITERAL_CSTRING("yes"), // value - false, // is secure - false, // is httponly - true, // is session - INT64_MAX, // expiry time - &attrs, // originAttributes + "cookiemgr.test"_ns, // domain + "/foo"_ns, // path + "test2"_ns, // name + "yes"_ns, // value + false, // is secure + true, // is httponly + true, // is session + PR_Now() / PR_USEC_PER_SEC + 2, // expiry time + &attrs, // originAttributes nsICookie::SAMESITE_NONE, nsICookie::SCHEME_HTTPS))); + EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->AddNative("new.domain"_ns, // domain + "/rabbit"_ns, // path + "test3"_ns, // name + "yes"_ns, // value + false, // is secure + false, // is httponly + true, // is session + INT64_MAX, // expiry time + &attrs, // originAttributes + nsICookie::SAMESITE_NONE, + nsICookie::SCHEME_HTTPS))); // confirm using enumerator nsTArray> cookies; EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->GetCookies(cookies))); @@ -808,26 +808,24 @@ TEST(TestCookie, TestCookieMain) EXPECT_TRUE(CheckResult(cookie.get(), MUST_NOT_CONTAIN, "test2=yes")); // check CountCookiesFromHost() uint32_t hostCookies = 0; - EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost( - NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies))); + EXPECT_TRUE(NS_SUCCEEDED( + cookieMgr2->CountCookiesFromHost("cookiemgr.test"_ns, &hostCookies))); EXPECT_EQ(hostCookies, 2u); // check CookieExistsNative() using the third cookie bool found; EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative( - NS_LITERAL_CSTRING("new.domain"), NS_LITERAL_CSTRING("/rabbit"), - NS_LITERAL_CSTRING("test3"), &attrs, &found))); + "new.domain"_ns, "/rabbit"_ns, "test3"_ns, &attrs, &found))); EXPECT_TRUE(found); // sleep four seconds, to make sure the second cookie has expired PR_Sleep(4 * PR_TicksPerSecond()); // check that both CountCookiesFromHost() and CookieExistsNative() count the // expired cookie - EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CountCookiesFromHost( - NS_LITERAL_CSTRING("cookiemgr.test"), &hostCookies))); + EXPECT_TRUE(NS_SUCCEEDED( + cookieMgr2->CountCookiesFromHost("cookiemgr.test"_ns, &hostCookies))); EXPECT_EQ(hostCookies, 2u); EXPECT_TRUE(NS_SUCCEEDED(cookieMgr2->CookieExistsNative( - NS_LITERAL_CSTRING("cookiemgr.test"), NS_LITERAL_CSTRING("/foo"), - NS_LITERAL_CSTRING("test2"), &attrs, &found))); + "cookiemgr.test"_ns, "/foo"_ns, "test2"_ns, &attrs, &found))); EXPECT_TRUE(found); // double-check RemoveAll() using the enumerator EXPECT_TRUE(NS_SUCCEEDED(cookieMgr->RemoveAll())); @@ -844,14 +842,14 @@ TEST(TestCookie, TestCookieMain) nsAutoCString name; nsAutoCString expected; for (int32_t i = 0; i < 60; ++i) { - name = NS_LITERAL_CSTRING("test"); + name = "test"_ns; name.AppendInt(i); - name += NS_LITERAL_CSTRING("=creation"); + name += "=creation"_ns; SetACookie(cookieService, "http://creation.ordering.tests/", name.get()); if (i >= 10) { expected += name; - if (i < 59) expected += NS_LITERAL_CSTRING("; "); + if (i < 59) expected += "; "_ns; } } GetACookie(cookieService, "http://creation.ordering.tests/", cookie); @@ -860,13 +858,13 @@ TEST(TestCookie, TestCookieMain) cookieMgr->RemoveAll(); for (int32_t i = 0; i < 60; ++i) { - name = NS_LITERAL_CSTRING("test"); + name = "test"_ns; name.AppendInt(i); - name += NS_LITERAL_CSTRING("=delete_non_security"); + name += "=delete_non_security"_ns; // Create 50 cookies that include the secure flag. if (i < 50) { - name += NS_LITERAL_CSTRING("; secure"); + name += "; secure"_ns; SetACookie(cookieService, "https://creation.ordering.tests/", name.get()); } else { // non-security cookies will be removed beside the latest cookie that be diff --git a/netwerk/test/gtest/TestHeaders.cpp b/netwerk/test/gtest/TestHeaders.cpp index 52af2b4864fd..0da6b06c7001 100644 --- a/netwerk/test/gtest/TestHeaders.cpp +++ b/netwerk/test/gtest/TestHeaders.cpp @@ -8,10 +8,9 @@ TEST(TestHeaders, DuplicateHSTS) // effective value is the value of the first item. It is not merged as other // headers are. mozilla::net::nsHttpHeaderArray headers; - nsresult rv = - headers.SetHeaderFromNet(mozilla::net::nsHttp::Strict_Transport_Security, - NS_LITERAL_CSTRING("Strict_Transport_Security"), - NS_LITERAL_CSTRING("max-age=360"), true); + nsresult rv = headers.SetHeaderFromNet( + mozilla::net::nsHttp::Strict_Transport_Security, + "Strict_Transport_Security"_ns, "max-age=360"_ns, true); ASSERT_EQ(rv, NS_OK); nsAutoCString h; @@ -20,8 +19,8 @@ TEST(TestHeaders, DuplicateHSTS) ASSERT_EQ(h.get(), "max-age=360"); rv = headers.SetHeaderFromNet(mozilla::net::nsHttp::Strict_Transport_Security, - NS_LITERAL_CSTRING("Strict_Transport_Security"), - NS_LITERAL_CSTRING("max-age=720"), true); + "Strict_Transport_Security"_ns, + "max-age=720"_ns, true); ASSERT_EQ(rv, NS_OK); rv = headers.GetHeader(mozilla::net::nsHttp::Strict_Transport_Security, h); diff --git a/netwerk/test/gtest/TestHttpResponseHead.cpp b/netwerk/test/gtest/TestHttpResponseHead.cpp index 60e3f33bcc69..fb4a94baf2d6 100644 --- a/netwerk/test/gtest/TestHttpResponseHead.cpp +++ b/netwerk/test/gtest/TestHttpResponseHead.cpp @@ -18,20 +18,15 @@ TEST(TestHttpResponseHead, Bug1636930) mozilla::UniquePtr msg(new IPC::Message(MSG_ROUTING_NONE, 0)); mozilla::net::nsHttpResponseHead origHead; - origHead.ParseStatusLine(NS_LITERAL_CSTRING("HTTP/1.1 200 OK")); - Unused << origHead.ParseHeaderLine( - NS_LITERAL_CSTRING("content-type: text/plain")); - Unused << origHead.ParseHeaderLine(NS_LITERAL_CSTRING("etag: Just testing")); - Unused << origHead.ParseHeaderLine( - NS_LITERAL_CSTRING("cache-control: max-age=99999")); - Unused << origHead.ParseHeaderLine( - NS_LITERAL_CSTRING("accept-ranges: bytes")); - Unused << origHead.ParseHeaderLine( - NS_LITERAL_CSTRING("content-length: 1408")); - Unused << origHead.ParseHeaderLine(NS_LITERAL_CSTRING("connection: close")); - Unused << origHead.ParseHeaderLine(NS_LITERAL_CSTRING("server: httpd.js")); - Unused << origHead.ParseHeaderLine( - NS_LITERAL_CSTRING("date: Tue, 12 May 2020 09:24:23 GMT")); + origHead.ParseStatusLine("HTTP/1.1 200 OK"_ns); + Unused << origHead.ParseHeaderLine("content-type: text/plain"_ns); + Unused << origHead.ParseHeaderLine("etag: Just testing"_ns); + Unused << origHead.ParseHeaderLine("cache-control: max-age=99999"_ns); + Unused << origHead.ParseHeaderLine("accept-ranges: bytes"_ns); + Unused << origHead.ParseHeaderLine("content-length: 1408"_ns); + Unused << origHead.ParseHeaderLine("connection: close"_ns); + Unused << origHead.ParseHeaderLine("server: httpd.js"_ns); + Unused << origHead.ParseHeaderLine("date: Tue, 12 May 2020 09:24:23 GMT"_ns); IPC::ParamTraits::Write(msg.get(), origHead); diff --git a/netwerk/test/gtest/TestInputStreamTransport.cpp b/netwerk/test/gtest/TestInputStreamTransport.cpp index a880f4b76359..ac133cab16f4 100644 --- a/netwerk/test/gtest/TestInputStreamTransport.cpp +++ b/netwerk/test/gtest/TestInputStreamTransport.cpp @@ -72,8 +72,7 @@ NS_IMPL_ISUPPORTS(BlockingSyncStream, nsIInputStream) // Testing a simple blocking stream. TEST(TestInputStreamTransport, BlockingNotAsync) { - RefPtr stream = - new BlockingSyncStream(NS_LITERAL_CSTRING("Hello world")); + RefPtr stream = new BlockingSyncStream("Hello world"_ns); nsCOMPtr ais; CreateStream(stream.forget(), getter_AddRefs(ais)); @@ -177,7 +176,7 @@ NS_IMPL_ISUPPORTS(BlockingAsyncStream, nsIInputStream, nsIAsyncInputStream) TEST(TestInputStreamTransport, BlockingAsync) { RefPtr stream = - new BlockingAsyncStream(NS_LITERAL_CSTRING("Hello world")); + new BlockingAsyncStream("Hello world"_ns); nsCOMPtr ais; CreateStream(stream.forget(), getter_AddRefs(ais)); diff --git a/netwerk/test/gtest/TestMozURL.cpp b/netwerk/test/gtest/TestMozURL.cpp index dcd3e3bc4490..de0d69f28d75 100644 --- a/netwerk/test/gtest/TestMozURL.cpp +++ b/netwerk/test/gtest/TestMozURL.cpp @@ -39,8 +39,7 @@ TEST(TestMozURL, Getters) ASSERT_TRUE(url->Ref().EqualsLiteral("ref")); url = nullptr; - ASSERT_EQ(MozURL::Init(getter_AddRefs(url), NS_LITERAL_CSTRING("")), - NS_ERROR_MALFORMED_URI); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url), ""_ns), NS_ERROR_MALFORMED_URI); ASSERT_EQ(url, nullptr); } @@ -53,13 +52,13 @@ TEST(TestMozURL, MutatorChain) RefPtr url2; ASSERT_EQ(url->Mutate() - .SetScheme(NS_LITERAL_CSTRING("https")) - .SetUsername(NS_LITERAL_CSTRING("newuser")) - .SetPassword(NS_LITERAL_CSTRING("newpass")) - .SetHostname(NS_LITERAL_CSTRING("test")) - .SetFilePath(NS_LITERAL_CSTRING("new/file/path")) - .SetQuery(NS_LITERAL_CSTRING("bla")) - .SetRef(NS_LITERAL_CSTRING("huh")) + .SetScheme("https"_ns) + .SetUsername("newuser"_ns) + .SetPassword("newpass"_ns) + .SetHostname("test"_ns) + .SetFilePath("new/file/path"_ns) + .SetQuery("bla"_ns) + .SetRef("huh"_ns) .Finalize(getter_AddRefs(url2)), NS_OK); @@ -76,7 +75,7 @@ TEST(TestMozURL, MutatorFinalizeTwice) RefPtr url2; MozURL::Mutator mut = url->Mutate(); - mut.SetScheme(NS_LITERAL_CSTRING("https")); // Change the scheme to https + mut.SetScheme("https"_ns); // Change the scheme to https ASSERT_EQ(mut.Finalize(getter_AddRefs(url2)), NS_OK); ASSERT_TRUE(url2->Spec().EqualsLiteral( "https://user:pass@example.com/path?query#ref")); @@ -96,11 +95,11 @@ TEST(TestMozURL, MutatorErrorStatus) // Test that trying to set the scheme to a bad value will get you an error MozURL::Mutator mut = url->Mutate(); - mut.SetScheme(NS_LITERAL_CSTRING("!@#$%^&*(")); + mut.SetScheme("!@#$%^&*("_ns); ASSERT_EQ(mut.GetStatus(), NS_ERROR_MALFORMED_URI); // Test that the mutator will not work after one faulty operation - mut.SetScheme(NS_LITERAL_CSTRING("test")); + mut.SetScheme("test"_ns); ASSERT_EQ(mut.GetStatus(), NS_ERROR_MALFORMED_URI); } @@ -113,9 +112,7 @@ TEST(TestMozURL, InitWithBase) ASSERT_TRUE(url->Spec().EqualsLiteral("https://example.net/a/b.html")); RefPtr url2; - ASSERT_EQ( - MozURL::Init(getter_AddRefs(url2), NS_LITERAL_CSTRING("c.png"), url), - NS_OK); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url2), "c.png"_ns, url), NS_OK); ASSERT_TRUE(url2->Spec().EqualsLiteral("https://example.net/a/c.png")); } @@ -142,9 +139,7 @@ TEST(TestMozURL, HostPort) ASSERT_TRUE(url->HostPort().EqualsLiteral("example.net:1234")); RefPtr url2; - url->Mutate() - .SetHostPort(NS_LITERAL_CSTRING("test:321")) - .Finalize(getter_AddRefs(url2)); + url->Mutate().SetHostPort("test:321"_ns).Finalize(getter_AddRefs(url2)); ASSERT_TRUE(url2->HostPort().EqualsLiteral("test:321")); ASSERT_TRUE( @@ -167,16 +162,14 @@ TEST(TestMozURL, Origin) ASSERT_TRUE(out.EqualsLiteral("https://example.net:1234")); RefPtr url2; - ASSERT_EQ( - MozURL::Init(getter_AddRefs(url2), NS_LITERAL_CSTRING("file:///tmp/foo")), - NS_OK); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url2), "file:///tmp/foo"_ns), NS_OK); url2->Origin(out); ASSERT_TRUE(out.EqualsLiteral("file:///tmp/foo")); RefPtr url3; ASSERT_EQ( MozURL::Init(getter_AddRefs(url3), - NS_LITERAL_CSTRING( + nsLiteralCString( "moz-extension://53711a8f-65ed-e742-9671-1f02e267c0bc/" "foo/bar.html")), NS_OK); @@ -185,16 +178,13 @@ TEST(TestMozURL, Origin) "moz-extension://53711a8f-65ed-e742-9671-1f02e267c0bc")); RefPtr url4; - ASSERT_EQ(MozURL::Init(getter_AddRefs(url4), - NS_LITERAL_CSTRING("resource://foo/bar.html")), + ASSERT_EQ(MozURL::Init(getter_AddRefs(url4), "resource://foo/bar.html"_ns), NS_OK); url4->Origin(out); ASSERT_TRUE(out.EqualsLiteral("resource://foo")); RefPtr url5; - ASSERT_EQ( - MozURL::Init(getter_AddRefs(url5), NS_LITERAL_CSTRING("about:home")), - NS_OK); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url5), "about:home"_ns), NS_OK); url5->Origin(out); ASSERT_TRUE(out.EqualsLiteral("about:home")); } @@ -210,16 +200,14 @@ TEST(TestMozURL, BaseDomain) ASSERT_TRUE(out.EqualsLiteral("example.net")); RefPtr url2; - ASSERT_EQ( - MozURL::Init(getter_AddRefs(url2), NS_LITERAL_CSTRING("file:///tmp/foo")), - NS_OK); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url2), "file:///tmp/foo"_ns), NS_OK); ASSERT_EQ(url2->BaseDomain(out), NS_OK); ASSERT_TRUE(out.EqualsLiteral("/tmp/foo")); RefPtr url3; ASSERT_EQ( MozURL::Init(getter_AddRefs(url3), - NS_LITERAL_CSTRING( + nsLiteralCString( "moz-extension://53711a8f-65ed-e742-9671-1f02e267c0bc/" "foo/bar.html")), NS_OK); @@ -227,16 +215,13 @@ TEST(TestMozURL, BaseDomain) ASSERT_TRUE(out.EqualsLiteral("53711a8f-65ed-e742-9671-1f02e267c0bc")); RefPtr url4; - ASSERT_EQ(MozURL::Init(getter_AddRefs(url4), - NS_LITERAL_CSTRING("resource://foo/bar.html")), + ASSERT_EQ(MozURL::Init(getter_AddRefs(url4), "resource://foo/bar.html"_ns), NS_OK); ASSERT_EQ(url4->BaseDomain(out), NS_OK); ASSERT_TRUE(out.EqualsLiteral("foo")); RefPtr url5; - ASSERT_EQ( - MozURL::Init(getter_AddRefs(url5), NS_LITERAL_CSTRING("about:home")), - NS_OK); + ASSERT_EQ(MozURL::Init(getter_AddRefs(url5), "about:home"_ns), NS_OK); ASSERT_EQ(url5->BaseDomain(out), NS_OK); ASSERT_TRUE(out.EqualsLiteral("about:home")); } @@ -246,7 +231,7 @@ namespace { bool OriginMatchesExpectedOrigin(const nsACString& aOrigin, const nsACString& aExpectedOrigin) { if (aExpectedOrigin.Equals("null") && - StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("moz-nullprincipal"))) { + StringBeginsWith(aOrigin, "moz-nullprincipal"_ns)) { return true; } return aOrigin == aExpectedOrigin; @@ -329,7 +314,7 @@ TEST(TestMozURL, UrlTestData) NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR, getter_AddRefs(file)); ASSERT_EQ(rv, NS_OK); - rv = file->Append(NS_LITERAL_STRING("urltestdata.json")); + rv = file->Append(u"urltestdata.json"_ns); ASSERT_EQ(rv, NS_OK); bool exists; diff --git a/netwerk/test/gtest/TestSocketTransportService.cpp b/netwerk/test/gtest/TestSocketTransportService.cpp index ddc3a31982db..ce8c301c7da6 100644 --- a/netwerk/test/gtest/TestSocketTransportService.cpp +++ b/netwerk/test/gtest/TestSocketTransportService.cpp @@ -29,84 +29,52 @@ TEST(TestSocketTransportService, PortRemappingPreferenceReading) }; // Ill-formed prefs - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING(";"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING(" ;"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("; "))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("foo"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING(" foo"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING(" foo "))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("10=20;"))); - - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1="))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1,="))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-="))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-,="))); - - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1=2,"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1=2-3"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-2,=3"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-2,3"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-2,3-4"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-2,3-4,"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-2,3-4="))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("10000000=10"))); - - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1=2;3"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-4=2;3"))); - ASSERT_FALSE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1-4=2;3="))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-foo=2;3=15"))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-4=foo;3=15"))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-4=2;foo=15"))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-4=2;3=foo"))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-4=2x3=15"))); - ASSERT_FALSE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1+4=2;3=15"))); + ASSERT_FALSE(sts->UpdatePortRemapPreference(";"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference(" ;"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("; "_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("foo"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference(" foo"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference(" foo "_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("10=20;"_ns)); + + ASSERT_FALSE(sts->UpdatePortRemapPreference("1"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1="_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1,="_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-="_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-,="_ns)); + + ASSERT_FALSE(sts->UpdatePortRemapPreference("1=2,"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1=2-3"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-2,=3"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-2,3"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-2,3-4"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-2,3-4,"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-2,3-4="_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("10000000=10"_ns)); + + ASSERT_FALSE(sts->UpdatePortRemapPreference("1=2;3"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=2;3"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=2;3="_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-foo=2;3=15"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=foo;3=15"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=2;foo=15"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=2;3=foo"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1-4=2x3=15"_ns)); + ASSERT_FALSE(sts->UpdatePortRemapPreference("1+4=2;3=15"_ns)); // Well-formed prefs - ASSERT_TRUE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("1=2"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("1=2"_ns)); ASSERT_TRUE(CheckPortRemap(1, 2)); ASSERT_TRUE(CheckPortRemap(2, 2)); ASSERT_TRUE(CheckPortRemap(3, 3)); - ASSERT_TRUE( - sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING("10=20"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("10=20"_ns)); ASSERT_TRUE(CheckPortRemap(1, 1)); ASSERT_TRUE(CheckPortRemap(2, 2)); ASSERT_TRUE(CheckPortRemap(3, 3)); ASSERT_TRUE(CheckPortRemap(10, 20)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("100-200=1000"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("100-200=1000"_ns)); ASSERT_TRUE(CheckPortRemap(10, 10)); ASSERT_TRUE(CheckPortRemap(99, 99)); ASSERT_TRUE(CheckPortRemap(100, 1000)); @@ -114,8 +82,7 @@ TEST(TestSocketTransportService, PortRemappingPreferenceReading) ASSERT_TRUE(CheckPortRemap(200, 1000)); ASSERT_TRUE(CheckPortRemap(201, 201)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("100-200,500=1000"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("100-200,500=1000"_ns)); ASSERT_TRUE(CheckPortRemap(10, 10)); ASSERT_TRUE(CheckPortRemap(99, 99)); ASSERT_TRUE(CheckPortRemap(100, 1000)); @@ -126,8 +93,7 @@ TEST(TestSocketTransportService, PortRemappingPreferenceReading) ASSERT_TRUE(CheckPortRemap(500, 1000)); ASSERT_TRUE(CheckPortRemap(501, 501)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("1-3=10;5-8,12=20"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("1-3=10;5-8,12=20"_ns)); ASSERT_TRUE(CheckPortRemap(1, 10)); ASSERT_TRUE(CheckPortRemap(2, 10)); ASSERT_TRUE(CheckPortRemap(3, 10)); @@ -137,35 +103,32 @@ TEST(TestSocketTransportService, PortRemappingPreferenceReading) ASSERT_TRUE(CheckPortRemap(11, 11)); ASSERT_TRUE(CheckPortRemap(12, 20)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("80=8080;443=8080"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("80=8080;443=8080"_ns)); ASSERT_TRUE(CheckPortRemap(80, 8080)); ASSERT_TRUE(CheckPortRemap(443, 8080)); // Later rules rewrite earlier rules - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("10=100;10=200"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("10=100;10=200"_ns)); ASSERT_TRUE(CheckPortRemap(10, 200)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("10-20=100;10-20=200"))); + ASSERT_TRUE( + sts->UpdatePortRemapPreference("10-20=100;10-20=200"_ns)); ASSERT_TRUE(CheckPortRemap(10, 200)); ASSERT_TRUE(CheckPortRemap(20, 200)); - ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING("10-20=100;15=200"))); + ASSERT_TRUE(sts->UpdatePortRemapPreference("10-20=100;15=200"_ns)); ASSERT_TRUE(CheckPortRemap(10, 100)); ASSERT_TRUE(CheckPortRemap(15, 200)); ASSERT_TRUE(CheckPortRemap(20, 100)); ASSERT_TRUE(sts->UpdatePortRemapPreference( - NS_LITERAL_CSTRING(" 100 - 200 = 1000 ; 150 = 2000 "))); + " 100 - 200 = 1000 ; 150 = 2000 "_ns)); ASSERT_TRUE(CheckPortRemap(100, 1000)); ASSERT_TRUE(CheckPortRemap(150, 2000)); ASSERT_TRUE(CheckPortRemap(200, 1000)); // Turn off any mapping - ASSERT_TRUE(sts->UpdatePortRemapPreference(NS_LITERAL_CSTRING(""))); + ASSERT_TRUE(sts->UpdatePortRemapPreference(""_ns)); for (uint32_t port = 0; port < 65536; ++port) { ASSERT_TRUE(CheckPortRemap((uint16_t)port, (uint16_t)port)); } diff --git a/netwerk/test/gtest/TestStandardURL.cpp b/netwerk/test/gtest/TestStandardURL.cpp index ab459054fa45..f4245540fcb8 100644 --- a/netwerk/test/gtest/TestStandardURL.cpp +++ b/netwerk/test/gtest/TestStandardURL.cpp @@ -19,65 +19,55 @@ TEST(TestStandardURL, Simple) { nsCOMPtr url; ASSERT_EQ(NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) + .SetSpec("http://example.com"_ns) .Finalize(url), NS_OK); ASSERT_TRUE(url); - ASSERT_EQ(NS_MutateURI(url) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) - .Finalize(url), + ASSERT_EQ(NS_MutateURI(url).SetSpec("http://example.com"_ns).Finalize(url), NS_OK); nsAutoCString out; ASSERT_EQ(url->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/")); + ASSERT_TRUE(out == "http://example.com/"_ns); - ASSERT_EQ(url->Resolve(NS_LITERAL_CSTRING("foo.html?q=45"), out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/foo.html?q=45")); + ASSERT_EQ(url->Resolve("foo.html?q=45"_ns, out), NS_OK); + ASSERT_TRUE(out == "http://example.com/foo.html?q=45"_ns); - ASSERT_EQ( - NS_MutateURI(url).SetScheme(NS_LITERAL_CSTRING("foo")).Finalize(url), - NS_OK); + ASSERT_EQ(NS_MutateURI(url).SetScheme("foo"_ns).Finalize(url), NS_OK); ASSERT_EQ(url->GetScheme(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("foo")); + ASSERT_TRUE(out == "foo"_ns); ASSERT_EQ(url->GetHost(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("example.com")); - ASSERT_EQ(NS_MutateURI(url) - .SetHost(NS_LITERAL_CSTRING("www.yahoo.com")) - .Finalize(url), - NS_OK); + ASSERT_TRUE(out == "example.com"_ns); + ASSERT_EQ(NS_MutateURI(url).SetHost("www.yahoo.com"_ns).Finalize(url), NS_OK); ASSERT_EQ(url->GetHost(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("www.yahoo.com")); + ASSERT_TRUE(out == "www.yahoo.com"_ns); ASSERT_EQ(NS_MutateURI(url) - .SetPathQueryRef(NS_LITERAL_CSTRING( + .SetPathQueryRef(nsLiteralCString( "/some-path/one-the-net/about.html?with-a-query#for-you")) .Finalize(url), NS_OK); ASSERT_EQ(url->GetPathQueryRef(out), NS_OK); ASSERT_TRUE(out == - NS_LITERAL_CSTRING( + nsLiteralCString( "/some-path/one-the-net/about.html?with-a-query#for-you")); ASSERT_EQ(NS_MutateURI(url) - .SetQuery(NS_LITERAL_CSTRING( + .SetQuery(nsLiteralCString( "a=b&d=c&what-ever-you-want-to-be-called=45")) .Finalize(url), NS_OK); ASSERT_EQ(url->GetQuery(out), NS_OK); - ASSERT_TRUE(out == - NS_LITERAL_CSTRING("a=b&d=c&what-ever-you-want-to-be-called=45")); + ASSERT_TRUE(out == "a=b&d=c&what-ever-you-want-to-be-called=45"_ns); - ASSERT_EQ(NS_MutateURI(url) - .SetRef(NS_LITERAL_CSTRING("#some-book-mark")) - .Finalize(url), + ASSERT_EQ(NS_MutateURI(url).SetRef("#some-book-mark"_ns).Finalize(url), NS_OK); ASSERT_EQ(url->GetRef(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("some-book-mark")); + ASSERT_TRUE(out == "some-book-mark"_ns); } TEST(TestStandardURL, NormalizeGood) @@ -258,38 +248,33 @@ TEST(TestStandardURL, From_test_standardurldotjs) MOZ_GTEST_BENCH(TestStandardURL, DISABLED_Perf, [] { nsCOMPtr url; ASSERT_EQ(NS_OK, NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) + .SetSpec("http://example.com"_ns) .Finalize(url)); nsAutoCString out; for (int i = COUNT; i; --i) { - ASSERT_EQ(NS_MutateURI(url) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) - .Finalize(url), + ASSERT_EQ(NS_MutateURI(url).SetSpec("http://example.com"_ns).Finalize(url), NS_OK); ASSERT_EQ(url->GetSpec(out), NS_OK); - url->Resolve(NS_LITERAL_CSTRING("foo.html?q=45"), out); - mozilla::Unused - << NS_MutateURI(url).SetScheme(NS_LITERAL_CSTRING("foo")).Finalize(url); + url->Resolve("foo.html?q=45"_ns, out); + mozilla::Unused << NS_MutateURI(url).SetScheme("foo"_ns).Finalize(url); url->GetScheme(out); - mozilla::Unused << NS_MutateURI(url) - .SetHost(NS_LITERAL_CSTRING("www.yahoo.com")) - .Finalize(url); + mozilla::Unused + << NS_MutateURI(url).SetHost("www.yahoo.com"_ns).Finalize(url); url->GetHost(out); mozilla::Unused << NS_MutateURI(url) - .SetPathQueryRef(NS_LITERAL_CSTRING( + .SetPathQueryRef(nsLiteralCString( "/some-path/one-the-net/about.html?with-a-query#for-you")) .Finalize(url); url->GetPathQueryRef(out); mozilla::Unused << NS_MutateURI(url) - .SetQuery(NS_LITERAL_CSTRING( + .SetQuery(nsLiteralCString( "a=b&d=c&what-ever-you-want-to-be-called=45")) .Finalize(url); url->GetQuery(out); - mozilla::Unused << NS_MutateURI(url) - .SetRef(NS_LITERAL_CSTRING("#some-book-mark")) - .Finalize(url); + mozilla::Unused + << NS_MutateURI(url).SetRef("#some-book-mark"_ns).Finalize(url); url->GetRef(out); } }); @@ -336,34 +321,34 @@ TEST(TestStandardURL, Mutator) nsAutoCString out; nsCOMPtr uri; nsresult rv = NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) + .SetSpec("http://example.com"_ns) .Finalize(uri); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/")); + ASSERT_TRUE(out == "http://example.com/"_ns); rv = NS_MutateURI(uri) - .SetScheme(NS_LITERAL_CSTRING("ftp")) - .SetHost(NS_LITERAL_CSTRING("mozilla.org")) - .SetPathQueryRef(NS_LITERAL_CSTRING("/path?query#ref")) + .SetScheme("ftp"_ns) + .SetHost("mozilla.org"_ns) + .SetPathQueryRef("/path?query#ref"_ns) .Finalize(uri); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("ftp://mozilla.org/path?query#ref")); + ASSERT_TRUE(out == "ftp://mozilla.org/path?query#ref"_ns); nsCOMPtr url; - rv = NS_MutateURI(uri).SetScheme(NS_LITERAL_CSTRING("https")).Finalize(url); + rv = NS_MutateURI(uri).SetScheme("https"_ns).Finalize(url); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(url->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("https://mozilla.org/path?query#ref")); + ASSERT_TRUE(out == "https://mozilla.org/path?query#ref"_ns); } TEST(TestStandardURL, Deserialize_Bug1392739) { mozilla::ipc::StandardURLParams standard_params; standard_params.urlType() = nsIStandardURL::URLTYPE_STANDARD; - standard_params.spec() = NS_LITERAL_CSTRING(""); + standard_params.spec() = ""_ns; standard_params.host() = mozilla::ipc::StandardURLSegment(4294967295, 1); mozilla::ipc::URIParams params(standard_params); diff --git a/netwerk/test/gtest/TestUDPSocket.cpp b/netwerk/test/gtest/TestUDPSocket.cpp index d864dc1725b4..84d26fbedf04 100644 --- a/netwerk/test/gtest/TestUDPSocket.cpp +++ b/netwerk/test/gtest/TestUDPSocket.cpp @@ -264,7 +264,7 @@ TEST(TestUDPSocket, TestUDPSocketMain) data.AppendElements((const uint8_t*)&dataBuffer, sizeof(uint32_t)); phase = TEST_OUTPUT_STREAM; - rv = client->Send(NS_LITERAL_CSTRING("127.0.0.1"), serverPort, data, &count); + rv = client->Send("127.0.0.1"_ns, serverPort, data, &count); ASSERT_TRUE(NS_SUCCEEDED(rv)); EXPECT_EQ(count, sizeof(uint32_t)); diff --git a/netwerk/test/gtest/TestURIMutator.cpp b/netwerk/test/gtest/TestURIMutator.cpp index 6ba3bb2f86df..7332591cfe71 100644 --- a/netwerk/test/gtest/TestURIMutator.cpp +++ b/netwerk/test/gtest/TestURIMutator.cpp @@ -14,87 +14,78 @@ TEST(TestURIMutator, Mutator) // and uses it to create a new URI. nsCOMPtr uri; nsresult rv = NS_MutateURI(NS_STANDARDURLMUTATOR_CONTRACTID) - .SetSpec(NS_LITERAL_CSTRING("http://example.com")) + .SetSpec("http://example.com"_ns) .Finalize(uri); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/")); + ASSERT_TRUE(out == "http://example.com/"_ns); // This test verifies that we can use NS_MutateURI to change a URI rv = NS_MutateURI(uri) - .SetScheme(NS_LITERAL_CSTRING("ftp")) - .SetHost(NS_LITERAL_CSTRING("mozilla.org")) - .SetPathQueryRef(NS_LITERAL_CSTRING("/path?query#ref")) + .SetScheme("ftp"_ns) + .SetHost("mozilla.org"_ns) + .SetPathQueryRef("/path?query#ref"_ns) .Finalize(uri); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("ftp://mozilla.org/path?query#ref")); + ASSERT_TRUE(out == "ftp://mozilla.org/path?query#ref"_ns); // This test verifies that we can pass nsIURL to Finalize, and nsCOMPtr url; - rv = NS_MutateURI(uri).SetScheme(NS_LITERAL_CSTRING("https")).Finalize(url); + rv = NS_MutateURI(uri).SetScheme("https"_ns).Finalize(url); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(url->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("https://mozilla.org/path?query#ref")); + ASSERT_TRUE(out == "https://mozilla.org/path?query#ref"_ns); // This test verifies that we can pass nsIURL** to Finalize. // We need to use the explicit template because it's actually passing // getter_AddRefs nsCOMPtr url2; rv = NS_MutateURI(url) - .SetRef(NS_LITERAL_CSTRING("newref")) + .SetRef("newref"_ns) .Finalize(getter_AddRefs(url2)); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(url2->GetSpec(out), NS_OK); - ASSERT_TRUE(out == - NS_LITERAL_CSTRING("https://mozilla.org/path?query#newref")); + ASSERT_TRUE(out == "https://mozilla.org/path?query#newref"_ns); // This test verifies that we can pass nsIURI** to Finalize. // No need to be explicit. auto functionSetRef = [](nsIURI* aURI, nsIURI** aResult) -> nsresult { - return NS_MutateURI(aURI) - .SetRef(NS_LITERAL_CSTRING("originalRef")) - .Finalize(aResult); + return NS_MutateURI(aURI).SetRef("originalRef"_ns).Finalize(aResult); }; nsCOMPtr newURI; rv = functionSetRef(url2, getter_AddRefs(newURI)); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(newURI->GetSpec(out), NS_OK); - ASSERT_TRUE(out == - NS_LITERAL_CSTRING("https://mozilla.org/path?query#originalRef")); + ASSERT_TRUE(out == "https://mozilla.org/path?query#originalRef"_ns); // This test verifies that we can pass nsIURI** to Finalize. nsCOMPtr uri2; - rv = NS_MutateURI(url2) - .SetQuery(NS_LITERAL_CSTRING("newquery")) - .Finalize(getter_AddRefs(uri2)); + rv = + NS_MutateURI(url2).SetQuery("newquery"_ns).Finalize(getter_AddRefs(uri2)); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri2->GetSpec(out), NS_OK); - ASSERT_TRUE(out == - NS_LITERAL_CSTRING("https://mozilla.org/path?newquery#newref")); + ASSERT_TRUE(out == "https://mozilla.org/path?newquery#newref"_ns); // This test verifies that we can pass nsIURI** to Finalize. // No need to be explicit. auto functionSetQuery = [](nsIURI* aURI, nsIURL** aResult) -> nsresult { - return NS_MutateURI(aURI) - .SetQuery(NS_LITERAL_CSTRING("originalQuery")) - .Finalize(aResult); + return NS_MutateURI(aURI).SetQuery("originalQuery"_ns).Finalize(aResult); }; nsCOMPtr newURL; rv = functionSetQuery(uri2, getter_AddRefs(newURL)); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(newURL->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING( - "https://mozilla.org/path?originalQuery#newref")); + ASSERT_TRUE(out == "https://mozilla.org/path?originalQuery#newref"_ns); // Check that calling Finalize twice will fail. NS_MutateURI mutator(newURL); rv = mutator.SetQuery(EmptyCString()).Finalize(uri2); ASSERT_EQ(rv, NS_OK); ASSERT_EQ(uri2->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("https://mozilla.org/path#newref")); + ASSERT_TRUE(out == "https://mozilla.org/path#newref"_ns); nsCOMPtr uri3; rv = mutator.Finalize(uri3); ASSERT_EQ(rv, NS_ERROR_NOT_AVAILABLE); @@ -113,12 +104,11 @@ TEST(TestURIMutator, OnAnyThread) nsCOMPtr task = NS_NewRunnableFunction("gtest-OnAnyThread", []() { nsCOMPtr uri; - nsresult rv = NS_NewURI(getter_AddRefs(uri), - NS_LITERAL_CSTRING("http://example.com")); + nsresult rv = NS_NewURI(getter_AddRefs(uri), "http://example.com"_ns); ASSERT_EQ(rv, NS_OK); nsAutoCString out; ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/")); + ASSERT_TRUE(out == "http://example.com/"_ns); }); EXPECT_TRUE(task); @@ -126,12 +116,11 @@ TEST(TestURIMutator, OnAnyThread) } nsCOMPtr uri; - nsresult rv = - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("http://example.com")); + nsresult rv = NS_NewURI(getter_AddRefs(uri), "http://example.com"_ns); ASSERT_EQ(rv, NS_OK); nsAutoCString out; ASSERT_EQ(uri->GetSpec(out), NS_OK); - ASSERT_TRUE(out == NS_LITERAL_CSTRING("http://example.com/")); + ASSERT_TRUE(out == "http://example.com/"_ns); pool->Shutdown(); diff --git a/netwerk/url-classifier/UrlClassifierCommon.cpp b/netwerk/url-classifier/UrlClassifierCommon.cpp index cc5d6ebb0451..6b5aad7477e2 100644 --- a/netwerk/url-classifier/UrlClassifierCommon.cpp +++ b/netwerk/url-classifier/UrlClassifierCommon.cpp @@ -88,8 +88,8 @@ bool UrlClassifierCommon::ShouldEnableClassifier(nsIChannel* aChannel) { nsCString chanSpec = chanURI->GetSpecOrDefault(); chanSpec.Truncate( std::min(chanSpec.Length(), UrlClassifierCommon::sMaxSpecLength)); - nsCString topWinSpec = topWinURI ? topWinURI->GetSpecOrDefault() - : NS_LITERAL_CSTRING("(null)"); + nsCString topWinSpec = + topWinURI ? topWinURI->GetSpecOrDefault() : "(null)"_ns; topWinSpec.Truncate( std::min(topWinSpec.Length(), UrlClassifierCommon::sMaxSpecLength)); UC_LOG( @@ -255,7 +255,7 @@ nsresult UrlClassifierCommon::SetBlockedContent(nsIChannel* channel, ClassifierBlockingErrorCodeToConsoleMessage(aErrorCode, category); } else { message = "UnsafeUriBlocked"; - category = NS_LITERAL_CSTRING("Safe Browsing"); + category = "Safe Browsing"_ns; } nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, category, doc, @@ -322,9 +322,8 @@ nsresult UrlClassifierCommon::CreatePairwiseWhiteListURI(nsIChannel* aChannel, rv = chanPrincipal->GetBaseDomain(resourceDomain); NS_ENSURE_SUCCESS(rv, rv); - nsAutoCString whitelistEntry = NS_LITERAL_CSTRING("http://") + pageHostname + - NS_LITERAL_CSTRING("/?resource=") + - resourceDomain; + nsAutoCString whitelistEntry = + "http://"_ns + pageHostname + "/?resource="_ns + resourceDomain; UC_LOG( ("CreatePairwiseWhiteListURI: Looking for %s in the whitelist " "(channel=%p)", @@ -474,9 +473,8 @@ bool UrlClassifierCommon::IsAllowListed(nsIChannel* aChannel) { } nsCOMPtr uri; - nsresult rv = - ios->NewURI(NS_LITERAL_CSTRING("http://allowlisted.example.com"), - nullptr, nullptr, getter_AddRefs(uri)); + nsresult rv = ios->NewURI("http://allowlisted.example.com"_ns, nullptr, + nullptr, getter_AddRefs(uri)); if (NS_WARN_IF(NS_FAILED(rv))) { return false; } diff --git a/netwerk/url-classifier/UrlClassifierFeatureCryptominingAnnotation.cpp b/netwerk/url-classifier/UrlClassifierFeatureCryptominingAnnotation.cpp index 21d2e8e76824..6dd41c9b6062 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureCryptominingAnnotation.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureCryptominingAnnotation.cpp @@ -41,17 +41,16 @@ StaticRefPtr UrlClassifierFeatureCryptominingAnnotation:: UrlClassifierFeatureCryptominingAnnotation() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(CRYPTOMINING_ANNOTATION_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_WHITELIST), - NS_LITERAL_CSTRING( + nsLiteralCString(CRYPTOMINING_ANNOTATION_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_WHITELIST), + nsLiteralCString( URLCLASSIFIER_CRYPTOMINING_ANNOTATION_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING( + nsLiteralCString( URLCLASSIFIER_CRYPTOMINING_ANNOTATION_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_CRYPTOMINING_ANNOTATION_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_CRYPTOMINING_ANNOTATION_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_SKIP_URLS)) { -} + nsLiteralCString(TABLE_CRYPTOMINING_ANNOTATION_BLACKLIST_PREF), + nsLiteralCString(TABLE_CRYPTOMINING_ANNOTATION_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_ANNOTATION_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureCryptominingAnnotation::Name() { return CRYPTOMINING_ANNOTATION_FEATURE_NAME; @@ -132,7 +131,7 @@ UrlClassifierFeatureCryptominingAnnotation::ProcessChannel( static std::vector sClassificationData = { - {NS_LITERAL_CSTRING("content-cryptomining-track-"), + {"content-cryptomining-track-"_ns, nsIClassifiedChannel::ClassificationFlags:: CLASSIFIED_CRYPTOMINING_CONTENT}, }; diff --git a/netwerk/url-classifier/UrlClassifierFeatureCryptominingProtection.cpp b/netwerk/url-classifier/UrlClassifierFeatureCryptominingProtection.cpp index ea783f39dfb1..93c883b378ec 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureCryptominingProtection.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureCryptominingProtection.cpp @@ -40,14 +40,14 @@ StaticRefPtr UrlClassifierFeatureCryptominingProtection:: UrlClassifierFeatureCryptominingProtection() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(CRYPTOMINING_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_WHITELIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_CRYPTOMINING_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_CRYPTOMINING_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_CRYPTOMINING_SKIP_URLS)) {} + nsLiteralCString(CRYPTOMINING_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_WHITELIST), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_BLACKLIST_TEST_ENTRIES), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_WHITELIST_TEST_ENTRIES), + nsLiteralCString(TABLE_CRYPTOMINING_BLACKLIST_PREF), + nsLiteralCString(TABLE_CRYPTOMINING_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_CRYPTOMINING_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureCryptominingProtection::Name() { return CRYPTOMINING_FEATURE_NAME; diff --git a/netwerk/url-classifier/UrlClassifierFeatureFactory.cpp b/netwerk/url-classifier/UrlClassifierFeatureFactory.cpp index 85674fa725b0..967ef63a3550 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureFactory.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureFactory.cpp @@ -307,16 +307,16 @@ struct BlockingErrorCode { static const BlockingErrorCode sBlockingErrorCodes[] = { {NS_ERROR_TRACKING_URI, nsIWebProgressListener::STATE_BLOCKED_TRACKING_CONTENT, - "TrackerUriBlocked", NS_LITERAL_CSTRING("Tracking Protection")}, + "TrackerUriBlocked", "Tracking Protection"_ns}, {NS_ERROR_FINGERPRINTING_URI, nsIWebProgressListener::STATE_BLOCKED_FINGERPRINTING_CONTENT, - "TrackerUriBlocked", NS_LITERAL_CSTRING("Tracking Protection")}, + "TrackerUriBlocked", "Tracking Protection"_ns}, {NS_ERROR_CRYPTOMINING_URI, nsIWebProgressListener::STATE_BLOCKED_CRYPTOMINING_CONTENT, - "TrackerUriBlocked", NS_LITERAL_CSTRING("Tracking Protection")}, + "TrackerUriBlocked", "Tracking Protection"_ns}, {NS_ERROR_SOCIALTRACKING_URI, nsIWebProgressListener::STATE_BLOCKED_SOCIALTRACKING_CONTENT, - "TrackerUriBlocked", NS_LITERAL_CSTRING("Tracking Protection")}, + "TrackerUriBlocked", "Tracking Protection"_ns}, }; } // namespace diff --git a/netwerk/url-classifier/UrlClassifierFeatureFingerprintingAnnotation.cpp b/netwerk/url-classifier/UrlClassifierFeatureFingerprintingAnnotation.cpp index c2d582d9bf48..723d9e8bca23 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureFingerprintingAnnotation.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureFingerprintingAnnotation.cpp @@ -41,17 +41,17 @@ StaticRefPtr UrlClassifierFeatureFingerprintingAnnotation:: UrlClassifierFeatureFingerprintingAnnotation() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(FINGERPRINTING_ANNOTATION_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_FINGERPRINTING_ANNOTATION_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_FINGERPRINTING_ANNOTATION_WHITELIST), - NS_LITERAL_CSTRING( + nsLiteralCString(FINGERPRINTING_ANNOTATION_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_ANNOTATION_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_ANNOTATION_WHITELIST), + nsLiteralCString( URLCLASSIFIER_FINGERPRINTING_ANNOTATION_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING( + nsLiteralCString( URLCLASSIFIER_FINGERPRINTING_ANNOTATION_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_FINGERPRINTING_ANNOTATION_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_FINGERPRINTING_ANNOTATION_WHITELIST_PREF), - NS_LITERAL_CSTRING( - URLCLASSIFIER_FINGERPRINTING_ANNOTATION_SKIP_URLS)) {} + nsLiteralCString(TABLE_FINGERPRINTING_ANNOTATION_BLACKLIST_PREF), + nsLiteralCString(TABLE_FINGERPRINTING_ANNOTATION_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_ANNOTATION_SKIP_URLS)) { +} /* static */ const char* UrlClassifierFeatureFingerprintingAnnotation::Name() { return FINGERPRINTING_ANNOTATION_FEATURE_NAME; @@ -138,7 +138,7 @@ UrlClassifierFeatureFingerprintingAnnotation::ProcessChannel( static std::vector sClassificationData = { - {NS_LITERAL_CSTRING("content-fingerprinting-track-"), + {"content-fingerprinting-track-"_ns, nsIClassifiedChannel::ClassificationFlags:: CLASSIFIED_FINGERPRINTING_CONTENT}, }; diff --git a/netwerk/url-classifier/UrlClassifierFeatureFingerprintingProtection.cpp b/netwerk/url-classifier/UrlClassifierFeatureFingerprintingProtection.cpp index 04833419e054..7fa5dca2195e 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureFingerprintingProtection.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureFingerprintingProtection.cpp @@ -40,16 +40,14 @@ StaticRefPtr UrlClassifierFeatureFingerprintingProtection:: UrlClassifierFeatureFingerprintingProtection() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(FINGERPRINTING_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_FINGERPRINTING_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_FINGERPRINTING_WHITELIST), - NS_LITERAL_CSTRING( - URLCLASSIFIER_FINGERPRINTING_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING( - URLCLASSIFIER_FINGERPRINTING_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_FINGERPRINTING_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_FINGERPRINTING_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_FINGERPRINTING_SKIP_URLS)) {} + nsLiteralCString(FINGERPRINTING_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_WHITELIST), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_BLACKLIST_TEST_ENTRIES), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_WHITELIST_TEST_ENTRIES), + nsLiteralCString(TABLE_FINGERPRINTING_BLACKLIST_PREF), + nsLiteralCString(TABLE_FINGERPRINTING_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_FINGERPRINTING_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureFingerprintingProtection::Name() { return FINGERPRINTING_FEATURE_NAME; diff --git a/netwerk/url-classifier/UrlClassifierFeatureLoginReputation.cpp b/netwerk/url-classifier/UrlClassifierFeatureLoginReputation.cpp index 7dbe6e7af85c..d9aa61451f57 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureLoginReputation.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureLoginReputation.cpp @@ -22,15 +22,14 @@ StaticRefPtr gFeatureLoginReputation; } // namespace UrlClassifierFeatureLoginReputation::UrlClassifierFeatureLoginReputation() - : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(LOGIN_REPUTATION_FEATURE_NAME), - EmptyCString(), // blacklist tables - NS_LITERAL_CSTRING(PREF_PASSWORD_ALLOW_TABLE), - EmptyCString(), // blacklist pref - EmptyCString(), // whitelist pref - EmptyCString(), // blacklist pref table name - EmptyCString(), // whitelist pref table name - EmptyCString()) // skip host pref + : UrlClassifierFeatureBase(nsLiteralCString(LOGIN_REPUTATION_FEATURE_NAME), + EmptyCString(), // blacklist tables + nsLiteralCString(PREF_PASSWORD_ALLOW_TABLE), + EmptyCString(), // blacklist pref + EmptyCString(), // whitelist pref + EmptyCString(), // blacklist pref table name + EmptyCString(), // whitelist pref table name + EmptyCString()) // skip host pref {} /* static */ const char* UrlClassifierFeatureLoginReputation::Name() { diff --git a/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingAnnotation.cpp b/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingAnnotation.cpp index 791876d1badc..f0f78543999a 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingAnnotation.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingAnnotation.cpp @@ -41,17 +41,17 @@ StaticRefPtr UrlClassifierFeatureSocialTrackingAnnotation:: UrlClassifierFeatureSocialTrackingAnnotation() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(SOCIALTRACKING_ANNOTATION_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_WHITELIST), - NS_LITERAL_CSTRING( + nsLiteralCString(SOCIALTRACKING_ANNOTATION_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_WHITELIST), + nsLiteralCString( URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING( + nsLiteralCString( URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_SOCIALTRACKING_ANNOTATION_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_SOCIALTRACKING_ANNOTATION_WHITELIST_PREF), - NS_LITERAL_CSTRING( - URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_SKIP_URLS)) {} + nsLiteralCString(TABLE_SOCIALTRACKING_ANNOTATION_BLACKLIST_PREF), + nsLiteralCString(TABLE_SOCIALTRACKING_ANNOTATION_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_ANNOTATION_SKIP_URLS)) { +} /* static */ const char* UrlClassifierFeatureSocialTrackingAnnotation::Name() { return SOCIALTRACKING_ANNOTATION_FEATURE_NAME; @@ -134,13 +134,13 @@ UrlClassifierFeatureSocialTrackingAnnotation::ProcessChannel( static std::vector sClassificationData = { - {NS_LITERAL_CSTRING("social-tracking-protection-facebook-"), + {"social-tracking-protection-facebook-"_ns, nsIClassifiedChannel::ClassificationFlags:: CLASSIFIED_SOCIALTRACKING_FACEBOOK}, - {NS_LITERAL_CSTRING("social-tracking-protection-linkedin-"), + {"social-tracking-protection-linkedin-"_ns, nsIClassifiedChannel::ClassificationFlags:: CLASSIFIED_SOCIALTRACKING_LINKEDIN}, - {NS_LITERAL_CSTRING("social-tracking-protection-twitter-"), + {"social-tracking-protection-twitter-"_ns, nsIClassifiedChannel::ClassificationFlags:: CLASSIFIED_SOCIALTRACKING_TWITTER}, }; diff --git a/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingProtection.cpp b/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingProtection.cpp index 1f5ce17247e5..28451d03906e 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingProtection.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureSocialTrackingProtection.cpp @@ -40,16 +40,14 @@ StaticRefPtr UrlClassifierFeatureSocialTrackingProtection:: UrlClassifierFeatureSocialTrackingProtection() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(SOCIALTRACKING_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_SOCIALTRACKING_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_SOCIALTRACKING_WHITELIST), - NS_LITERAL_CSTRING( - URLCLASSIFIER_SOCIALTRACKING_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING( - URLCLASSIFIER_SOCIALTRACKING_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_SOCIALTRACKING_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_SOCIALTRACKING_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_SOCIALTRACKING_SKIP_URLS)) {} + nsLiteralCString(SOCIALTRACKING_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_WHITELIST), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_BLACKLIST_TEST_ENTRIES), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_WHITELIST_TEST_ENTRIES), + nsLiteralCString(TABLE_SOCIALTRACKING_BLACKLIST_PREF), + nsLiteralCString(TABLE_SOCIALTRACKING_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_SOCIALTRACKING_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureSocialTrackingProtection::Name() { return SOCIALTRACKING_FEATURE_NAME; diff --git a/netwerk/url-classifier/UrlClassifierFeatureTrackingAnnotation.cpp b/netwerk/url-classifier/UrlClassifierFeatureTrackingAnnotation.cpp index bae124a67e1d..09a5e2a3632f 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureTrackingAnnotation.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureTrackingAnnotation.cpp @@ -40,14 +40,14 @@ StaticRefPtr gFeatureTrackingAnnotation; UrlClassifierFeatureTrackingAnnotation::UrlClassifierFeatureTrackingAnnotation() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(TRACKING_ANNOTATION_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_ANNOTATION_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_ANNOTATION_WHITELIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_ANNOTATION_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(URLCLASSIFIER_ANNOTATION_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_ANNOTATION_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_ANNOTATION_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_ANNOTATION_SKIP_URLS)) {} + nsLiteralCString(TRACKING_ANNOTATION_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_ANNOTATION_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_ANNOTATION_WHITELIST), + nsLiteralCString(URLCLASSIFIER_ANNOTATION_BLACKLIST_TEST_ENTRIES), + nsLiteralCString(URLCLASSIFIER_ANNOTATION_WHITELIST_TEST_ENTRIES), + nsLiteralCString(TABLE_ANNOTATION_BLACKLIST_PREF), + nsLiteralCString(TABLE_ANNOTATION_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_TRACKING_ANNOTATION_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureTrackingAnnotation::Name() { return TRACKING_ANNOTATION_FEATURE_NAME; @@ -126,17 +126,14 @@ UrlClassifierFeatureTrackingAnnotation::ProcessChannel( static std::vector sClassificationData = { - {NS_LITERAL_CSTRING("ads-track-"), + {"ads-track-"_ns, nsIClassifiedChannel::ClassificationFlags::CLASSIFIED_TRACKING_AD}, - {NS_LITERAL_CSTRING("analytics-track-"), - nsIClassifiedChannel::ClassificationFlags:: - CLASSIFIED_TRACKING_ANALYTICS}, - {NS_LITERAL_CSTRING("social-track-"), - nsIClassifiedChannel::ClassificationFlags:: - CLASSIFIED_TRACKING_SOCIAL}, - {NS_LITERAL_CSTRING("content-track-"), - nsIClassifiedChannel::ClassificationFlags:: - CLASSIFIED_TRACKING_CONTENT}, + {"analytics-track-"_ns, nsIClassifiedChannel::ClassificationFlags:: + CLASSIFIED_TRACKING_ANALYTICS}, + {"social-track-"_ns, nsIClassifiedChannel::ClassificationFlags:: + CLASSIFIED_TRACKING_SOCIAL}, + {"content-track-"_ns, nsIClassifiedChannel::ClassificationFlags:: + CLASSIFIED_TRACKING_CONTENT}, }; uint32_t flags = UrlClassifierCommon::TablesToClassificationFlags( diff --git a/netwerk/url-classifier/UrlClassifierFeatureTrackingProtection.cpp b/netwerk/url-classifier/UrlClassifierFeatureTrackingProtection.cpp index 9b599c982a67..413a7d2eb8c8 100644 --- a/netwerk/url-classifier/UrlClassifierFeatureTrackingProtection.cpp +++ b/netwerk/url-classifier/UrlClassifierFeatureTrackingProtection.cpp @@ -37,14 +37,14 @@ StaticRefPtr gFeatureTrackingProtection; UrlClassifierFeatureTrackingProtection::UrlClassifierFeatureTrackingProtection() : UrlClassifierFeatureBase( - NS_LITERAL_CSTRING(TRACKING_PROTECTION_FEATURE_NAME), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_BLACKLIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_WHITELIST), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_BLACKLIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_WHITELIST_TEST_ENTRIES), - NS_LITERAL_CSTRING(TABLE_TRACKING_BLACKLIST_PREF), - NS_LITERAL_CSTRING(TABLE_TRACKING_WHITELIST_PREF), - NS_LITERAL_CSTRING(URLCLASSIFIER_TRACKING_PROTECTION_SKIP_URLS)) {} + nsLiteralCString(TRACKING_PROTECTION_FEATURE_NAME), + nsLiteralCString(URLCLASSIFIER_TRACKING_BLACKLIST), + nsLiteralCString(URLCLASSIFIER_TRACKING_WHITELIST), + nsLiteralCString(URLCLASSIFIER_TRACKING_BLACKLIST_TEST_ENTRIES), + nsLiteralCString(URLCLASSIFIER_TRACKING_WHITELIST_TEST_ENTRIES), + nsLiteralCString(TABLE_TRACKING_BLACKLIST_PREF), + nsLiteralCString(TABLE_TRACKING_WHITELIST_PREF), + nsLiteralCString(URLCLASSIFIER_TRACKING_PROTECTION_SKIP_URLS)) {} /* static */ const char* UrlClassifierFeatureTrackingProtection::Name() { return TRACKING_PROTECTION_FEATURE_NAME; diff --git a/netwerk/url-classifier/nsChannelClassifier.cpp b/netwerk/url-classifier/nsChannelClassifier.cpp index 024b067461af..8dffe74aee99 100644 --- a/netwerk/url-classifier/nsChannelClassifier.cpp +++ b/netwerk/url-classifier/nsChannelClassifier.cpp @@ -122,8 +122,7 @@ void nsChannelClassifier::Start() { if (NS_FAILED(rv)) { // If we aren't getting a callback for any reason, assume a good verdict and // make sure we resume the channel if necessary. - OnClassifyComplete(NS_OK, NS_LITERAL_CSTRING(""), NS_LITERAL_CSTRING(""), - NS_LITERAL_CSTRING("")); + OnClassifyComplete(NS_OK, ""_ns, ""_ns, ""_ns); } } diff --git a/parser/html/nsHtml5StreamParser.cpp b/parser/html/nsHtml5StreamParser.cpp index 242396b29e1d..c589f25b66dc 100644 --- a/parser/html/nsHtml5StreamParser.cpp +++ b/parser/html/nsHtml5StreamParser.cpp @@ -1844,7 +1844,7 @@ void nsHtml5StreamParser::ContinueAfterScripts(nsHtml5Tokenizer* aTokenizer, mTokenizer->setLineNumber(speculation->GetStartLineNumber()); nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM Events"), + nsIScriptError::warningFlag, "DOM Events"_ns, mExecutor->GetDocument(), nsContentUtils::eDOM_PROPERTIES, "SpeculationFailed", nsTArray(), nullptr, EmptyString(), speculation->GetStartLineNumber()); diff --git a/parser/html/nsHtml5TreeOpExecutor.cpp b/parser/html/nsHtml5TreeOpExecutor.cpp index d315012c8ae2..16a80a81f044 100644 --- a/parser/html/nsHtml5TreeOpExecutor.cpp +++ b/parser/html/nsHtml5TreeOpExecutor.cpp @@ -819,18 +819,17 @@ void nsHtml5TreeOpExecutor::MaybeComplainAboutCharset(const char* aMsgId, mAlreadyComplainedAboutCharset = true; nsContentUtils::ReportToConsole( aError ? nsIScriptError::errorFlag : nsIScriptError::warningFlag, - NS_LITERAL_CSTRING("HTML parser"), mDocument, - nsContentUtils::eHTMLPARSER_PROPERTIES, aMsgId, nsTArray(), - nullptr, EmptyString(), aLineNumber); + "HTML parser"_ns, mDocument, nsContentUtils::eHTMLPARSER_PROPERTIES, + aMsgId, nsTArray(), nullptr, EmptyString(), aLineNumber); } void nsHtml5TreeOpExecutor::ComplainAboutBogusProtocolCharset(Document* aDoc) { NS_ASSERTION(!mAlreadyComplainedAboutCharset, "How come we already managed to complain?"); mAlreadyComplainedAboutCharset = true; - nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("HTML parser"), aDoc, - nsContentUtils::eHTMLPARSER_PROPERTIES, "EncProtocolUnsupported"); + nsContentUtils::ReportToConsole(nsIScriptError::errorFlag, "HTML parser"_ns, + aDoc, nsContentUtils::eHTMLPARSER_PROPERTIES, + "EncProtocolUnsupported"); } void nsHtml5TreeOpExecutor::MaybeComplainAboutDeepTree(uint32_t aLineNumber) { @@ -839,7 +838,7 @@ void nsHtml5TreeOpExecutor::MaybeComplainAboutDeepTree(uint32_t aLineNumber) { } mAlreadyComplainedAboutDeepTree = true; nsContentUtils::ReportToConsole( - nsIScriptError::errorFlag, NS_LITERAL_CSTRING("HTML parser"), mDocument, + nsIScriptError::errorFlag, "HTML parser"_ns, mDocument, nsContentUtils::eHTMLPARSER_PROPERTIES, "errDeepTree", nsTArray(), nullptr, EmptyString(), aLineNumber); } diff --git a/parser/html/nsHtml5TreeOperation.cpp b/parser/html/nsHtml5TreeOperation.cpp index 05355fbe9f4c..c4b7bad1e4c8 100644 --- a/parser/html/nsHtml5TreeOperation.cpp +++ b/parser/html/nsHtml5TreeOperation.cpp @@ -1118,8 +1118,8 @@ nsresult nsHtml5TreeOperation::Perform(nsHtml5TreeOpExecutor* aBuilder, klass.AppendLiteral(" error"); element->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, klass, true); } else { - element->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, - NS_LITERAL_STRING("error"), true); + element->SetAttr(kNameSpaceID_None, nsGkAtoms::_class, u"error"_ns, + true); } nsresult rv; @@ -1155,7 +1155,7 @@ nsresult nsHtml5TreeOperation::Perform(nsHtml5TreeOpExecutor* aBuilder, nsresult operator()(const opAddLineNumberId& aOperation) { Element* element = (*(aOperation.mElement))->AsElement(); int32_t lineNumber = aOperation.mLineNumber; - nsAutoString val(NS_LITERAL_STRING("line")); + nsAutoString val(u"line"_ns); val.AppendInt(lineNumber); element->SetAttr(kNameSpaceID_None, nsGkAtoms::id, val, true); return NS_OK; diff --git a/parser/html/nsParserUtils.cpp b/parser/html/nsParserUtils.cpp index e73953352c9a..17b69a728d97 100644 --- a/parser/html/nsParserUtils.cpp +++ b/parser/html/nsParserUtils.cpp @@ -63,7 +63,7 @@ nsParserUtils::Sanitize(const nsAString& aFromStr, uint32_t aFlags, nsCOMPtr encoder = do_createDocumentEncoder("text/html"); - encoder->NativeInit(document, NS_LITERAL_STRING("text/html"), + encoder->NativeInit(document, u"text/html"_ns, nsIDocumentEncoder::OutputDontRewriteEncodingDeclaration | nsIDocumentEncoder::OutputNoScriptContent | nsIDocumentEncoder::OutputEncodeBasicEntities | diff --git a/parser/htmlparser/nsExpatDriver.cpp b/parser/htmlparser/nsExpatDriver.cpp index fe2c2d21b21f..7da15ade8c66 100644 --- a/parser/htmlparser/nsExpatDriver.cpp +++ b/parser/htmlparser/nsExpatDriver.cpp @@ -328,8 +328,8 @@ void nsExpatDriver::HandleStartElementForSystemPrincipal( error.AppendLiteral("> created from entity value."); nsContentUtils::ReportToConsoleNonLocalized( - error, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("XML Document"), - doc, nullptr, EmptyString(), lineNumber, colNumber); + error, nsIScriptError::warningFlag, "XML Document"_ns, doc, nullptr, + EmptyString(), lineNumber, colNumber); } } @@ -694,7 +694,7 @@ nsresult nsExpatDriver::OpenInputStreamFromExternalDTD(const char16_t* aFPIStr, NS_ENSURE_SUCCESS(rv, rv); CopyUTF8toUTF16(absURL, aAbsURL); - channel->SetContentType(NS_LITERAL_CSTRING("application/xml")); + channel->SetContentType("application/xml"_ns); return channel->Open(aStream); } diff --git a/parser/htmlparser/nsHTMLTags.cpp b/parser/htmlparser/nsHTMLTags.cpp index 96a92f828415..512eeb7d6cd4 100644 --- a/parser/htmlparser/nsHTMLTags.cpp +++ b/parser/htmlparser/nsHTMLTags.cpp @@ -146,9 +146,9 @@ void nsHTMLTags::TestTagTable() { } // Make sure we don't find things that aren't there - id = StringTagToId(NS_LITERAL_STRING("@")); + id = StringTagToId(u"@"_ns); NS_ASSERTION(id == eHTMLTag_userdefined, "found @"); - id = StringTagToId(NS_LITERAL_STRING("zzzzz")); + id = StringTagToId(u"zzzzz"_ns); NS_ASSERTION(id == eHTMLTag_userdefined, "found zzzzz"); atom = NS_Atomize("@"); diff --git a/parser/htmlparser/nsParser.cpp b/parser/htmlparser/nsParser.cpp index 1e33cf13ea8f..a3d0022b070e 100644 --- a/parser/htmlparser/nsParser.cpp +++ b/parser/htmlparser/nsParser.cpp @@ -795,7 +795,7 @@ nsresult nsParser::Parse(const nsAString& aSourceBuffer, void* aKey, // end fix for 40143 pc->mContextType = CParserContext::eCTString; - pc->SetMimeType(NS_LITERAL_CSTRING("application/xml")); + pc->SetMimeType("application/xml"_ns); pc->mDTDMode = eDTDMode_full_standards; mUnusedInput.Truncate(); @@ -876,7 +876,7 @@ nsParser::ParseFragment(const nsAString& aSourceBuffer, } else { // Add an end tag chunk, so expat will read the whole source buffer, // and not worry about ']]' etc. - result = Parse(aSourceBuffer + NS_LITERAL_STRING("DidBuildContent(); if (NS_SUCCEEDED(result)) { diff --git a/security/apps/AppSignatureVerification.cpp b/security/apps/AppSignatureVerification.cpp index dc650832ec71..9cd036c7be56 100644 --- a/security/apps/AppSignatureVerification.cpp +++ b/security/apps/AppSignatureVerification.cpp @@ -417,7 +417,7 @@ nsresult ParseSF(const char* filebuf, SECOidTag digestAlgorithm, const char* nextLineStart = filebuf; nsresult rv = - CheckManifestVersion(nextLineStart, NS_LITERAL_CSTRING(JAR_SF_HEADER)); + CheckManifestVersion(nextLineStart, nsLiteralCString(JAR_SF_HEADER)); if (NS_FAILED(rv)) { return rv; } @@ -492,7 +492,7 @@ nsresult ParseMF(const char* filebuf, nsIZipReader* zip, const char* nextLineStart = filebuf; nsresult rv = - CheckManifestVersion(nextLineStart, NS_LITERAL_CSTRING(JAR_MF_HEADER)); + CheckManifestVersion(nextLineStart, nsLiteralCString(JAR_MF_HEADER)); if (NS_FAILED(rv)) { return rv; } @@ -1078,9 +1078,8 @@ nsresult VerifyCOSESignature(AppTrustedRoot aTrustedRoot, nsIZipReader* aZip, // Read COSE signature file. nsAutoCString coseFilename; ScopedAutoSECItem coseBuffer; - nsresult rv = - FindAndLoadOneEntry(aZip, NS_LITERAL_CSTRING(JAR_COSE_SEARCH_STRING), - coseFilename, coseBuffer); + nsresult rv = FindAndLoadOneEntry( + aZip, nsLiteralCString(JAR_COSE_SEARCH_STRING), coseFilename, coseBuffer); if (NS_FAILED(rv)) { return required ? NS_ERROR_SIGNED_JAR_WRONG_SIGNATURE : NS_OK; } @@ -1088,7 +1087,7 @@ nsresult VerifyCOSESignature(AppTrustedRoot aTrustedRoot, nsIZipReader* aZip, // Verify COSE signature. nsAutoCString mfFilename; ScopedAutoSECItem manifestBuffer; - rv = FindAndLoadOneEntry(aZip, NS_LITERAL_CSTRING(JAR_COSE_MF_SEARCH_STRING), + rv = FindAndLoadOneEntry(aZip, nsLiteralCString(JAR_COSE_MF_SEARCH_STRING), mfFilename, manifestBuffer); if (NS_FAILED(rv)) { return required ? NS_ERROR_SIGNED_JAR_WRONG_SIGNATURE : rv; @@ -1144,7 +1143,7 @@ nsresult VerifyPK7Signature( // Signature (SF) file nsAutoCString sfFilename; ScopedAutoSECItem sfBuffer; - rv = FindAndLoadOneEntry(aZip, NS_LITERAL_CSTRING(JAR_SF_SEARCH_STRING), + rv = FindAndLoadOneEntry(aZip, nsLiteralCString(JAR_SF_SEARCH_STRING), sfFilename, sfBuffer); if (NS_FAILED(rv)) { return required ? NS_ERROR_SIGNED_JAR_MANIFEST_INVALID : NS_OK; @@ -1192,7 +1191,7 @@ nsresult VerifyPK7Signature( ScopedAutoSECItem manifestBuffer; Digest mfCalculatedDigest; nsAutoCString mfFilename; - rv = FindAndLoadOneEntry(aZip, NS_LITERAL_CSTRING(JAR_MF_SEARCH_STRING), + rv = FindAndLoadOneEntry(aZip, nsLiteralCString(JAR_MF_SEARCH_STRING), mfFilename, manifestBuffer, digestToUse, &mfCalculatedDigest); if (NS_FAILED(rv)) { diff --git a/security/manager/pki/nsNSSDialogs.cpp b/security/manager/pki/nsNSSDialogs.cpp index 3236fdb34964..7aadbc32ed96 100644 --- a/security/manager/pki/nsNSSDialogs.cpp +++ b/security/manager/pki/nsNSSDialogs.cpp @@ -127,8 +127,7 @@ nsNSSDialogs::ConfirmDownloadCACert(nsIInterfaceRequestor* ctx, return rv; } - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("importConfirmed"), - importConfirmed); + rv = retVals->GetPropertyAsBool(u"importConfirmed"_ns, importConfirmed); if (NS_FAILED(rv)) { return rv; } @@ -139,14 +138,12 @@ nsNSSDialogs::ConfirmDownloadCACert(nsIInterfaceRequestor* ctx, } bool trustForSSL = false; - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("trustForSSL"), - &trustForSSL); + rv = retVals->GetPropertyAsBool(u"trustForSSL"_ns, &trustForSSL); if (NS_FAILED(rv)) { return rv; } bool trustForEmail = false; - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("trustForEmail"), - &trustForEmail); + rv = retVals->GetPropertyAsBool(u"trustForEmail"_ns, &trustForEmail); if (NS_FAILED(rv)) { return rv; } @@ -234,20 +231,18 @@ nsNSSDialogs::ChooseCertificate(const nsACString& hostname, int32_t port, return rv; } - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("rememberSelection"), + rv = retVals->GetPropertyAsBool(u"rememberSelection"_ns, rememberClientAuthCertificate); if (NS_FAILED(rv)) { return rv; } - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("certChosen"), - certificateChosen); + rv = retVals->GetPropertyAsBool(u"certChosen"_ns, certificateChosen); if (NS_FAILED(rv)) { return rv; } if (*certificateChosen) { - rv = retVals->GetPropertyAsUint32(NS_LITERAL_STRING("selectedIndex"), - selectedIndex); + rv = retVals->GetPropertyAsUint32(u"selectedIndex"_ns, selectedIndex); if (NS_FAILED(rv)) { return rv; } @@ -272,8 +267,7 @@ nsNSSDialogs::SetPKCS12FilePassword(nsIInterfaceRequestor* ctx, return rv; } - rv = retVals->GetPropertyAsBool(NS_LITERAL_STRING("confirmedPassword"), - confirmedPassword); + rv = retVals->GetPropertyAsBool(u"confirmedPassword"_ns, confirmedPassword); if (NS_FAILED(rv)) { return rv; } @@ -282,7 +276,7 @@ nsNSSDialogs::SetPKCS12FilePassword(nsIInterfaceRequestor* ctx, return NS_OK; } - return retVals->GetPropertyAsAString(NS_LITERAL_STRING("password"), password); + return retVals->GetPropertyAsAString(u"password"_ns, password); } NS_IMETHODIMP diff --git a/security/manager/ssl/CertBlocklist.cpp b/security/manager/ssl/CertBlocklist.cpp index 8973f410b271..b9a0f482ffac 100644 --- a/security/manager/ssl/CertBlocklist.cpp +++ b/security/manager/ssl/CertBlocklist.cpp @@ -165,7 +165,7 @@ nsresult CertBlocklist::Init() { mBackingFile = nullptr; return NS_OK; } - rv = mBackingFile->Append(NS_LITERAL_STRING("revocations.txt")); + rv = mBackingFile->Append(u"revocations.txt"_ns); if (NS_FAILED(rv)) { return rv; } @@ -404,8 +404,7 @@ CertBlocklist::SaveEntries() { return rv; } - rv = WriteLine(outputStream, - NS_LITERAL_CSTRING("# Auto generated contents. Do not edit.")); + rv = WriteLine(outputStream, "# Auto generated contents. Do not edit."_ns); if (NS_FAILED(rv)) { return rv; } @@ -430,7 +429,7 @@ CertBlocklist::SaveEntries() { // If it's a subject / public key block, write it straight out if (item.mItemMechanism == BlockBySubjectAndPubKey) { WriteLine(outputStream, encDN); - WriteLine(outputStream, NS_LITERAL_CSTRING("\t") + encOther); + WriteLine(outputStream, "\t"_ns + encOther); continue; } @@ -456,8 +455,7 @@ CertBlocklist::SaveEntries() { // Write serial data to the output stream for (auto iter = issuerSet->Iter(); !iter.Done(); iter.Next()) { - nsresult rv = WriteLine(outputStream, - NS_LITERAL_CSTRING(" ") + iter.Get()->GetKey()); + nsresult rv = WriteLine(outputStream, " "_ns + iter.Get()->GetKey()); if (NS_FAILED(rv)) { MOZ_LOG(gCertBlockPRLog, LogLevel::Warning, ("CertBlocklist::SaveEntries writing revocation data failed")); diff --git a/security/manager/ssl/ContentSignatureVerifier.cpp b/security/manager/ssl/ContentSignatureVerifier.cpp index abe4cbd40659..bcb673cf480e 100644 --- a/security/manager/ssl/ContentSignatureVerifier.cpp +++ b/security/manager/ssl/ContentSignatureVerifier.cpp @@ -150,8 +150,8 @@ nsresult ReadChainIntoCertList(const nsACString& aCertChain, bool inBlock = false; bool certFound = false; - const nsCString header = NS_LITERAL_CSTRING("-----BEGIN CERTIFICATE-----"); - const nsCString footer = NS_LITERAL_CSTRING("-----END CERTIFICATE-----"); + const nsCString header = "-----BEGIN CERTIFICATE-----"_ns; + const nsCString footer = "-----END CERTIFICATE-----"_ns; nsCWhitespaceTokenizerTemplate tokenizer(aCertChain); diff --git a/security/manager/ssl/DataStorage.cpp b/security/manager/ssl/DataStorage.cpp index 2ed14b781a16..520800ac7194 100644 --- a/security/manager/ssl/DataStorage.cpp +++ b/security/manager/ssl/DataStorage.cpp @@ -170,7 +170,7 @@ class DataStorageMemoryReporter final : public nsIMemoryReporter { NS_ConvertUTF16toUTF8(file).get()); Unused << aHandleReport->Callback( EmptyCString(), path, KIND_HEAP, UNITS_BYTES, amount, - NS_LITERAL_CSTRING("Memory used by PSM data storage cache."), aData); + "Memory used by PSM data storage cache."_ns, aData); } return NS_OK; } diff --git a/security/manager/ssl/OSReauthenticator.cpp b/security/manager/ssl/OSReauthenticator.cpp index c45da5ba4a1c..340103ad348e 100644 --- a/security/manager/ssl/OSReauthenticator.cpp +++ b/security/manager/ssl/OSReauthenticator.cpp @@ -139,21 +139,21 @@ bool IsAutoAdminLogonEnabled() { rv = regKey->Open( nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, - NS_LITERAL_STRING( - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), + nsLiteralString( + u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), nsIWindowsRegKey::ACCESS_READ); if (NS_FAILED(rv)) { return false; } nsAutoString value; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("AutoAdminLogon"), value); + rv = regKey->ReadStringValue(u"AutoAdminLogon"_ns, value); if (NS_FAILED(rv)) { return false; } regKey->Close(); - return value.Equals(NS_LITERAL_STRING("1")); + return value.Equals(u"1"_ns); } bool IsRequireSignonEnabled() { @@ -165,36 +165,33 @@ bool IsRequireSignonEnabled() { return true; } - rv = regKey->Open( - nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, - NS_LITERAL_STRING("System\\CurrentControlSet\\Control\\Power\\User\\Power" - "Schemes"), - nsIWindowsRegKey::ACCESS_READ); + rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, + u"System\\CurrentControlSet\\Control\\Power\\User\\Power" + "Schemes"_ns, + nsIWindowsRegKey::ACCESS_READ); if (NS_FAILED(rv)) { return true; } nsAutoString activePowerScheme; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("ActivePowerScheme"), - activePowerScheme); + rv = regKey->ReadStringValue(u"ActivePowerScheme"_ns, activePowerScheme); if (NS_FAILED(rv)) { return true; } regKey->Close(); - rv = regKey->Open( - nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, - NS_LITERAL_STRING("System\\CurrentControlSet\\Control\\Power\\User\\Power" - "Schemes\\") + - activePowerScheme + - NS_LITERAL_STRING("\\0e796bdb-100d-47d6-a2d5-f7d2daa51f51"), - nsIWindowsRegKey::ACCESS_READ); + rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_LOCAL_MACHINE, + u"System\\CurrentControlSet\\Control\\Power\\User\\Power" + "Schemes\\"_ns + + activePowerScheme + + u"\\0e796bdb-100d-47d6-a2d5-f7d2daa51f51"_ns, + nsIWindowsRegKey::ACCESS_READ); if (NS_FAILED(rv)) { return true; } uint32_t value; - rv = regKey->ReadIntValue(NS_LITERAL_STRING("ACSettingIndex"), &value); + rv = regKey->ReadIntValue(u"ACSettingIndex"_ns, &value); if (NS_FAILED(rv)) { return true; } diff --git a/security/manager/ssl/SSLServerCertVerification.cpp b/security/manager/ssl/SSLServerCertVerification.cpp index 429b216be8b5..8f7635e0af44 100644 --- a/security/manager/ssl/SSLServerCertVerification.cpp +++ b/security/manager/ssl/SSLServerCertVerification.cpp @@ -169,7 +169,7 @@ void InitializeSSLServerCertVerificationThreads() { (void)gCertVerificationThreadPool->SetIdleThreadLimit(5); (void)gCertVerificationThreadPool->SetIdleThreadTimeout(30 * 1000); (void)gCertVerificationThreadPool->SetThreadLimit(5); - (void)gCertVerificationThreadPool->SetName(NS_LITERAL_CSTRING("SSL Cert")); + (void)gCertVerificationThreadPool->SetName("SSL Cert"_ns); } // Called when the socket transport thread finishes, to destroy the thread @@ -422,8 +422,7 @@ static nsresult OverrideAllowedForHost( } nsCOMPtr uri; - nsresult rv = NS_NewURI(getter_AddRefs(uri), - NS_LITERAL_CSTRING("https://") + aHostname); + nsresult rv = NS_NewURI(getter_AddRefs(uri), "https://"_ns + aHostname); if (NS_FAILED(rv)) { MOZ_LOG(gPIPNSSLog, LogLevel::Debug, ("[0x%" PRIx64 "] Creating new URI failed", aPtrForLog)); @@ -489,8 +488,7 @@ static SECStatus BlockServerCertChangeForSpdy( MOZ_ASSERT(NS_SUCCEEDED(rv), "GetNegotiatedNPN() failed during renegotiation"); - if (NS_SUCCEEDED(rv) && - !StringBeginsWith(negotiatedNPN, NS_LITERAL_CSTRING("spdy/"))) { + if (NS_SUCCEEDED(rv) && !StringBeginsWith(negotiatedNPN, "spdy/"_ns)) { return SECSuccess; } // If GetNegotiatedNPN() failed we will assume spdy for safety's safe @@ -623,7 +621,7 @@ void GatherBaselineRequirementsTelemetry(const UniqueCERTCertList& certList) { BitwiseCast(currentName->name.other.data), currentName->name.other.len); nsDependentCString altNameWithoutWildcard(altName, 0); - if (StringBeginsWith(altNameWithoutWildcard, NS_LITERAL_CSTRING("*."))) { + if (StringBeginsWith(altNameWithoutWildcard, "*."_ns)) { altNameWithoutWildcard.Rebind(altName, 2); commonNameInSubjectAltNames |= TryMatchingWildcardSubjectAltName(commonName.get(), altName); diff --git a/security/manager/ssl/SharedSSLState.cpp b/security/manager/ssl/SharedSSLState.cpp index a1b1f729cd15..7dbab96ebf13 100644 --- a/security/manager/ssl/SharedSSLState.cpp +++ b/security/manager/ssl/SharedSSLState.cpp @@ -44,8 +44,7 @@ class MainThreadClearer : public SyncRunnableBase { nsCOMPtr icos = do_GetService(NS_CERTOVERRIDE_CONTRACTID); if (icos) { - icos->ClearValidityOverride( - NS_LITERAL_CSTRING("all:temporary-certificates"), 0); + icos->ClearValidityOverride("all:temporary-certificates"_ns, 0); } } diff --git a/security/manager/ssl/nsCertOverrideService.cpp b/security/manager/ssl/nsCertOverrideService.cpp index b39467f5acca..f325aa007700 100644 --- a/security/manager/ssl/nsCertOverrideService.cpp +++ b/security/manager/ssl/nsCertOverrideService.cpp @@ -162,7 +162,7 @@ nsresult nsCertOverrideService::Init() { nsresult rv = GetShutdownBarrier()->AddBlocker( this, NS_LITERAL_STRING(__FILE__), __LINE__, - NS_LITERAL_STRING("nsCertOverrideService shutdown")); + u"nsCertOverrideService shutdown"_ns); // If that failed, we're likely getting initialized during shutdown. NS_ENSURE_SUCCESS(rv, rv); @@ -202,7 +202,7 @@ nsCertOverrideService::Observe(nsISupports*, const char* aTopic, nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mSettingsFile)); if (NS_SUCCEEDED(rv)) { - mSettingsFile->AppendNative(NS_LITERAL_CSTRING(CERT_OVERRIDE_FILE_NAME)); + mSettingsFile->AppendNative(nsLiteralCString(CERT_OVERRIDE_FILE_NAME)); } else { mSettingsFile = nullptr; } @@ -731,7 +731,7 @@ void nsCertOverrideService::GetHostWithPort(const nsACString& aHostName, // nsIAsyncShutdownBlocker implementation NS_IMETHODIMP nsCertOverrideService::GetName(nsAString& aName) { - aName = NS_LITERAL_STRING("nsCertOverrideService: shutdown"); + aName = u"nsCertOverrideService: shutdown"_ns; return NS_OK; } diff --git a/security/manager/ssl/nsCertTree.cpp b/security/manager/ssl/nsCertTree.cpp index df60975d0462..c670968ecd23 100644 --- a/security/manager/ssl/nsCertTree.cpp +++ b/security/manager/ssl/nsCertTree.cpp @@ -888,7 +888,7 @@ nsCertTree::GetCellText(int32_t row, nsTreeColumn* col, nsAString& _retval) { treeArrayEl* el = GetThreadDescAtIndex(row); if (el) { - if (NS_LITERAL_STRING("certcol").Equals(colID)) + if (u"certcol"_ns.Equals(colID)) _retval.Assign(el->orgName); else _retval.Truncate(); @@ -920,42 +920,42 @@ nsCertTree::GetCellText(int32_t row, nsTreeColumn* col, nsAString& _retval) { } } - if (NS_LITERAL_STRING("certcol").Equals(colID)) { + if (u"certcol"_ns.Equals(colID)) { if (!cert) { rv = GetPIPNSSBundleString("CertNotStored", _retval); } else { rv = cert->GetDisplayName(_retval); } - } else if (NS_LITERAL_STRING("tokencol").Equals(colID) && cert) { + } else if (u"tokencol"_ns.Equals(colID) && cert) { rv = cert->GetTokenName(_retval); - } else if (NS_LITERAL_STRING("emailcol").Equals(colID) && cert) { + } else if (u"emailcol"_ns.Equals(colID) && cert) { rv = cert->GetEmailAddress(_retval); - } else if (NS_LITERAL_STRING("issuedcol").Equals(colID) && cert) { + } else if (u"issuedcol"_ns.Equals(colID) && cert) { nsCOMPtr validity; rv = cert->GetValidity(getter_AddRefs(validity)); if (NS_SUCCEEDED(rv)) { validity->GetNotBeforeLocalDay(_retval); } - } else if (NS_LITERAL_STRING("expiredcol").Equals(colID) && cert) { + } else if (u"expiredcol"_ns.Equals(colID) && cert) { nsCOMPtr validity; rv = cert->GetValidity(getter_AddRefs(validity)); if (NS_SUCCEEDED(rv)) { validity->GetNotAfterLocalDay(_retval); } - } else if (NS_LITERAL_STRING("serialnumcol").Equals(colID) && cert) { + } else if (u"serialnumcol"_ns.Equals(colID) && cert) { rv = cert->GetSerialNumber(_retval); - } else if (NS_LITERAL_STRING("sitecol").Equals(colID)) { + } else if (u"sitecol"_ns.Equals(colID)) { if (certdi->mTypeOfEntry == nsCertTreeDispInfo::host_port_override) { nsAutoCString hostPort; nsCertOverrideService::GetHostWithPort(certdi->mAsciiHost, certdi->mPort, hostPort); _retval = NS_ConvertUTF8toUTF16(hostPort); } else { - _retval = NS_LITERAL_STRING("*"); + _retval = u"*"_ns; } - } else if (NS_LITERAL_STRING("lifetimecol").Equals(colID)) { + } else if (u"lifetimecol"_ns.Equals(colID)) { const char* stringID = (certdi->mIsTemporary) ? "CertExceptionTemporary" : "CertExceptionPermanent"; rv = GetPIPNSSBundleString(stringID, _retval); diff --git a/security/manager/ssl/nsNSSCallbacks.cpp b/security/manager/ssl/nsNSSCallbacks.cpp index a04a10889e2f..1d41c40f8100 100644 --- a/security/manager/ssl/nsNSSCallbacks.cpp +++ b/security/manager/ssl/nsNSSCallbacks.cpp @@ -607,35 +607,35 @@ nsCString getKeaGroupName(uint32_t aKeaGroup) { nsCString groupName; switch (aKeaGroup) { case ssl_grp_ec_secp256r1: - groupName = NS_LITERAL_CSTRING("P256"); + groupName = "P256"_ns; break; case ssl_grp_ec_secp384r1: - groupName = NS_LITERAL_CSTRING("P384"); + groupName = "P384"_ns; break; case ssl_grp_ec_secp521r1: - groupName = NS_LITERAL_CSTRING("P521"); + groupName = "P521"_ns; break; case ssl_grp_ec_curve25519: - groupName = NS_LITERAL_CSTRING("x25519"); + groupName = "x25519"_ns; break; case ssl_grp_ffdhe_2048: - groupName = NS_LITERAL_CSTRING("FF 2048"); + groupName = "FF 2048"_ns; break; case ssl_grp_ffdhe_3072: - groupName = NS_LITERAL_CSTRING("FF 3072"); + groupName = "FF 3072"_ns; break; case ssl_grp_none: - groupName = NS_LITERAL_CSTRING("none"); + groupName = "none"_ns; break; case ssl_grp_ffdhe_custom: - groupName = NS_LITERAL_CSTRING("custom"); + groupName = "custom"_ns; break; // All other groups are not enabled in Firefox. See namedGroups in // nsNSSIOLayer.cpp. default: // This really shouldn't happen! MOZ_ASSERT_UNREACHABLE("Invalid key exchange group."); - groupName = NS_LITERAL_CSTRING("unknown group"); + groupName = "unknown group"_ns; } return groupName; } @@ -644,50 +644,50 @@ nsCString getSignatureName(uint32_t aSignatureScheme) { nsCString signatureName; switch (aSignatureScheme) { case ssl_sig_none: - signatureName = NS_LITERAL_CSTRING("none"); + signatureName = "none"_ns; break; case ssl_sig_rsa_pkcs1_sha1: - signatureName = NS_LITERAL_CSTRING("RSA-PKCS1-SHA1"); + signatureName = "RSA-PKCS1-SHA1"_ns; break; case ssl_sig_rsa_pkcs1_sha256: - signatureName = NS_LITERAL_CSTRING("RSA-PKCS1-SHA256"); + signatureName = "RSA-PKCS1-SHA256"_ns; break; case ssl_sig_rsa_pkcs1_sha384: - signatureName = NS_LITERAL_CSTRING("RSA-PKCS1-SHA384"); + signatureName = "RSA-PKCS1-SHA384"_ns; break; case ssl_sig_rsa_pkcs1_sha512: - signatureName = NS_LITERAL_CSTRING("RSA-PKCS1-SHA512"); + signatureName = "RSA-PKCS1-SHA512"_ns; break; case ssl_sig_ecdsa_secp256r1_sha256: - signatureName = NS_LITERAL_CSTRING("ECDSA-P256-SHA256"); + signatureName = "ECDSA-P256-SHA256"_ns; break; case ssl_sig_ecdsa_secp384r1_sha384: - signatureName = NS_LITERAL_CSTRING("ECDSA-P384-SHA384"); + signatureName = "ECDSA-P384-SHA384"_ns; break; case ssl_sig_ecdsa_secp521r1_sha512: - signatureName = NS_LITERAL_CSTRING("ECDSA-P521-SHA512"); + signatureName = "ECDSA-P521-SHA512"_ns; break; case ssl_sig_rsa_pss_sha256: - signatureName = NS_LITERAL_CSTRING("RSA-PSS-SHA256"); + signatureName = "RSA-PSS-SHA256"_ns; break; case ssl_sig_rsa_pss_sha384: - signatureName = NS_LITERAL_CSTRING("RSA-PSS-SHA384"); + signatureName = "RSA-PSS-SHA384"_ns; break; case ssl_sig_rsa_pss_sha512: - signatureName = NS_LITERAL_CSTRING("RSA-PSS-SHA512"); + signatureName = "RSA-PSS-SHA512"_ns; break; case ssl_sig_ecdsa_sha1: - signatureName = NS_LITERAL_CSTRING("ECDSA-SHA1"); + signatureName = "ECDSA-SHA1"_ns; break; case ssl_sig_rsa_pkcs1_sha1md5: - signatureName = NS_LITERAL_CSTRING("RSA-PKCS1-SHA1MD5"); + signatureName = "RSA-PKCS1-SHA1MD5"_ns; break; // All other groups are not enabled in Firefox. See sEnabledSignatureSchemes // in nsNSSIOLayer.cpp. default: // This really shouldn't happen! MOZ_ASSERT_UNREACHABLE("Invalid signature scheme."); - signatureName = NS_LITERAL_CSTRING("unknown signature"); + signatureName = "unknown signature"_ns; } return signatureName; } diff --git a/security/manager/ssl/nsNSSComponent.cpp b/security/manager/ssl/nsNSSComponent.cpp index 88d5b8effb85..6fe61301b911 100644 --- a/security/manager/ssl/nsNSSComponent.cpp +++ b/security/manager/ssl/nsNSSComponent.cpp @@ -433,8 +433,7 @@ static nsresult AccountHasFamilySafetyEnabled(bool& enabled) { // account for the first time, However, these sub-keys are not created // unless they are switched away from the default value. uint32_t parentalControlsOn; - rv = sidKey->ReadIntValue(NS_LITERAL_STRING("Parental Controls On"), - &parentalControlsOn); + rv = sidKey->ReadIntValue(u"Parental Controls On"_ns, &parentalControlsOn); if (NS_FAILED(rv)) { MOZ_LOG(gPIPNSSLog, LogLevel::Debug, ("couldn't read Parental Controls On")); @@ -2468,8 +2467,7 @@ nsresult nsNSSComponent::LogoutAuthenticatedPK11() { nsCOMPtr icos = do_GetService("@mozilla.org/security/certoverride;1"); if (icos) { - icos->ClearValidityOverride( - NS_LITERAL_CSTRING("all:temporary-certificates"), 0); + icos->ClearValidityOverride("all:temporary-certificates"_ns, 0); } nsCOMPtr svc = diff --git a/security/manager/ssl/nsNSSIOLayer.cpp b/security/manager/ssl/nsNSSIOLayer.cpp index a5317a9adb9b..85992b44ad68 100644 --- a/security/manager/ssl/nsNSSIOLayer.cpp +++ b/security/manager/ssl/nsNSSIOLayer.cpp @@ -1849,7 +1849,7 @@ SECStatus nsNSS_SSLGetClientAuthData(void* arg, PRFileDesc* socket, *pRetKey = nullptr; Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_CLIENT_CERT, - NS_LITERAL_STRING("requested"), 1); + u"requested"_ns, 1); RefPtr info( BitwiseCast(socket->higher->secret)); @@ -1909,8 +1909,8 @@ SECStatus nsNSS_SSLGetClientAuthData(void* arg, PRFileDesc* socket, *pRetKey = selectedKey.release(); // Make joinConnection prohibit joining after we've sent a client cert info->SetSentClientCert(); - Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_CLIENT_CERT, - NS_LITERAL_STRING("sent"), 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::SECURITY_CLIENT_CERT, u"sent"_ns, + 1); } return SECSuccess; diff --git a/security/manager/ssl/tests/gtest/DataStorageTest.cpp b/security/manager/ssl/tests/gtest/DataStorageTest.cpp index 1ebc29c010cf..58914616b850 100644 --- a/security/manager/ssl/tests/gtest/DataStorageTest.cpp +++ b/security/manager/ssl/tests/gtest/DataStorageTest.cpp @@ -39,8 +39,7 @@ TEST_F(psm_DataStorageTest, GetPutRemove) { // Don't re-use testKey / testValue here, to make sure that this works as // expected with objects that have the same semantic value but are not // literally the same object. - nsCString result = - storage->Get(NS_LITERAL_CSTRING("test"), DataStorage_Persistent); + nsCString result = storage->Get("test"_ns, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); // Get on Temporary/Private data with the same key should give nothing @@ -89,26 +88,20 @@ TEST_F(psm_DataStorageTest, GetPutRemove) { TEST_F(psm_DataStorageTest, InputValidation) { // Keys may not have tabs or newlines EXPECT_EQ(NS_ERROR_INVALID_ARG, - storage->Put(NS_LITERAL_CSTRING("key\thas tab"), testValue, - DataStorage_Persistent)); - nsCString result = - storage->Get(NS_LITERAL_CSTRING("key\thas tab"), DataStorage_Persistent); + storage->Put("key\thas tab"_ns, testValue, DataStorage_Persistent)); + nsCString result = storage->Get("key\thas tab"_ns, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); - EXPECT_EQ(NS_ERROR_INVALID_ARG, - storage->Put(NS_LITERAL_CSTRING("key has\nnewline"), testValue, - DataStorage_Persistent)); - result = storage->Get(NS_LITERAL_CSTRING("keyhas\nnewline"), - DataStorage_Persistent); + EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put("key has\nnewline"_ns, testValue, + DataStorage_Persistent)); + result = storage->Get("keyhas\nnewline"_ns, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); // Values may not have newlines - EXPECT_EQ(NS_ERROR_INVALID_ARG, - storage->Put(testKey, NS_LITERAL_CSTRING("value\nhas newline"), - DataStorage_Persistent)); + EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put(testKey, "value\nhas newline"_ns, + DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); // Values may have tabs EXPECT_TRUE(result.IsEmpty()); - EXPECT_EQ(NS_OK, storage->Put(testKey, - NS_LITERAL_CSTRING("val\thas tab; this is ok"), + EXPECT_EQ(NS_OK, storage->Put(testKey, "val\thas tab; this is ok"_ns, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("val\thas tab; this is ok", result.get()); diff --git a/security/manager/ssl/tests/gtest/TLSIntoleranceTest.cpp b/security/manager/ssl/tests/gtest/TLSIntoleranceTest.cpp index a50ddfbe300b..3e3096c8dbf5 100644 --- a/security/manager/ssl/tests/gtest/TLSIntoleranceTest.cpp +++ b/security/manager/ssl/tests/gtest/TLSIntoleranceTest.cpp @@ -318,8 +318,7 @@ TEST_F(psm_TLSIntoleranceTest, TLSPerSiteFallbackLimit) { ASSERT_TRUE( helpers.fallbackLimitReached(example_org, SSL_LIBRARY_VERSION_TLS_1_0)); - helpers.setInsecureFallbackSites( - NS_LITERAL_CSTRING("example.com,example.net")); + helpers.setInsecureFallbackSites("example.com,example.net"_ns); ASSERT_FALSE( helpers.fallbackLimitReached(example_com, SSL_LIBRARY_VERSION_TLS_1_2)); diff --git a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp b/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp index 91e1b1cfc10a..9ec0365fb0cc 100644 --- a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp +++ b/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp @@ -182,7 +182,7 @@ static void AddPathsFromFileInternal(SandboxBroker::Policy* aPolicy, line.EndReading(end); token_end = end; - if (FindInReadable(NS_LITERAL_CSTRING("include "), start, token_end)) { + if (FindInReadable("include "_ns, start, token_end)) { nsAutoCString includes(Substring(token_end, end)); for (const nsACString& includeGlob : includes.Split(' ')) { // Glob path might be relative, so add cwd if so. @@ -250,7 +250,7 @@ static void AddPathsFromFile(SandboxBroker::Policy* aPolicy, } static void AddLdconfigPaths(SandboxBroker::Policy* aPolicy) { - nsAutoCString ldConfig(NS_LITERAL_CSTRING("/etc/ld.so.conf")); + nsAutoCString ldConfig("/etc/ld.so.conf"_ns); AddPathsFromFile(aPolicy, ldConfig); } @@ -378,9 +378,9 @@ SandboxBrokerPolicyFactory::SandboxBrokerPolicyFactory() { // ~/.local/share (for themes) rv = homeDir->Clone(getter_AddRefs(confDir)); if (NS_SUCCEEDED(rv)) { - rv = confDir->AppendNative(NS_LITERAL_CSTRING(".local")); + rv = confDir->AppendNative(".local"_ns); if (NS_SUCCEEDED(rv)) { - rv = confDir->AppendNative(NS_LITERAL_CSTRING("share")); + rv = confDir->AppendNative("share"_ns); } if (NS_SUCCEEDED(rv)) { nsAutoCString tmpPath; @@ -394,7 +394,7 @@ SandboxBrokerPolicyFactory::SandboxBrokerPolicyFactory() { // ~/.fonts.conf (Fontconfig) rv = homeDir->Clone(getter_AddRefs(confDir)); if (NS_SUCCEEDED(rv)) { - rv = confDir->AppendNative(NS_LITERAL_CSTRING(".fonts.conf")); + rv = confDir->AppendNative(".fonts.conf"_ns); if (NS_SUCCEEDED(rv)) { nsAutoCString tmpPath; rv = confDir->GetNativePath(tmpPath); @@ -407,7 +407,7 @@ SandboxBrokerPolicyFactory::SandboxBrokerPolicyFactory() { // .pangorc rv = homeDir->Clone(getter_AddRefs(confDir)); if (NS_SUCCEEDED(rv)) { - rv = confDir->AppendNative(NS_LITERAL_CSTRING(".pangorc")); + rv = confDir->AppendNative(".pangorc"_ns); if (NS_SUCCEEDED(rv)) { nsAutoCString tmpPath; rv = confDir->GetNativePath(tmpPath); @@ -570,7 +570,7 @@ UniquePtr SandboxBrokerPolicyFactory::GetContentPolicy( nsCOMPtr workDir; rv = profileDir->Clone(getter_AddRefs(workDir)); if (NS_SUCCEEDED(rv)) { - rv = workDir->AppendNative(NS_LITERAL_CSTRING("chrome")); + rv = workDir->AppendNative("chrome"_ns); if (NS_SUCCEEDED(rv)) { nsAutoCString tmpPath; rv = workDir->GetNativePath(tmpPath); @@ -581,7 +581,7 @@ UniquePtr SandboxBrokerPolicyFactory::GetContentPolicy( } rv = profileDir->Clone(getter_AddRefs(workDir)); if (NS_SUCCEEDED(rv)) { - rv = workDir->AppendNative(NS_LITERAL_CSTRING("extensions")); + rv = workDir->AppendNative("extensions"_ns); if (NS_SUCCEEDED(rv)) { nsAutoCString tmpPath; rv = workDir->GetNativePath(tmpPath); diff --git a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp b/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp index a698c0d4c01e..4736669631d2 100644 --- a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp +++ b/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp @@ -91,7 +91,7 @@ static void CacheDirAndAutoClear(nsIProperties* aDirSvc, const char* aDirKey, MOZ_ALWAYS_SUCCEEDS(dirToCache->GetPath(**cacheVar)); // Convert network share path to format for sandbox policy. - if (Substring(**cacheVar, 0, 2).Equals(NS_LITERAL_STRING("\\\\"))) { + if (Substring(**cacheVar, 0, 2).Equals(u"\\\\"_ns)) { (*cacheVar)->InsertLiteral(u"??\\UNC", 1); } } @@ -588,7 +588,7 @@ void SandboxBroker::SetSecurityLevelForContentProcess(int32_t aSandboxLevel, // to the normal TEMP dir. However such failures should be pretty rare and // without this printing will not currently work. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_ANY, - sContentTempDir, NS_LITERAL_STRING("\\*")); + sContentTempDir, u"\\*"_ns); // We still have edge cases where the child at low integrity can't read some // files, so add a rule to allow read access to everything when required. @@ -602,29 +602,28 @@ void SandboxBroker::SetSecurityLevelForContentProcess(int32_t aSandboxLevel, } else { // Add rule to allow access to user specific fonts. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sLocalAppDataDir, - NS_LITERAL_STRING("\\Microsoft\\Windows\\Fonts\\*")); + sLocalAppDataDir, u"\\Microsoft\\Windows\\Fonts\\*"_ns); // Add rule to allow read access to installation directory. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sBinDir, NS_LITERAL_STRING("\\*")); + sBinDir, u"\\*"_ns); // Add rule to allow read access to the chrome directory within profile. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sProfileDir, NS_LITERAL_STRING("\\chrome\\*")); + sProfileDir, u"\\chrome\\*"_ns); // Add rule to allow read access to the extensions directory within profile. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sProfileDir, NS_LITERAL_STRING("\\extensions\\*")); + sProfileDir, u"\\extensions\\*"_ns); // Read access to a directory for system extension dev (see bug 1393805) AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sUserExtensionsDevDir, NS_LITERAL_STRING("\\*")); + sUserExtensionsDevDir, u"\\*"_ns); #ifdef ENABLE_SYSTEM_EXTENSION_DIRS // Add rule to allow read access to the per-user extensions directory. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_READONLY, - sUserExtensionsDir, NS_LITERAL_STRING("\\*")); + sUserExtensionsDir, u"\\*"_ns); #endif } @@ -1125,40 +1124,34 @@ bool SandboxBroker::SetSecurityLevelForPluginProcess(int32_t aSandboxLevel) { // Add rule to allow read / write access to a special plugin temp dir. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_ANY, - sPluginTempDir, NS_LITERAL_STRING("\\*")); + sPluginTempDir, u"\\*"_ns); if (aSandboxLevel >= 2) { // Level 2 and above uses low integrity, so we need to give write access to // the Flash directories. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_ANY, - sRoamingAppDataDir, - NS_LITERAL_STRING("\\Macromedia\\Flash Player\\*")); + sRoamingAppDataDir, u"\\Macromedia\\Flash Player\\*"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_ANY, - sLocalAppDataDir, - NS_LITERAL_STRING("\\Macromedia\\Flash Player\\*")); + sLocalAppDataDir, u"\\Macromedia\\Flash Player\\*"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_ANY, - sRoamingAppDataDir, - NS_LITERAL_STRING("\\Adobe\\Flash Player\\*")); + sRoamingAppDataDir, u"\\Adobe\\Flash Player\\*"_ns); // Access also has to be given to create the parent directories as they may // not exist. AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sRoamingAppDataDir, NS_LITERAL_STRING("\\Macromedia")); + sRoamingAppDataDir, u"\\Macromedia"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_QUERY, - sRoamingAppDataDir, NS_LITERAL_STRING("\\Macromedia\\")); + sRoamingAppDataDir, u"\\Macromedia\\"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sRoamingAppDataDir, - NS_LITERAL_STRING("\\Macromedia\\Flash Player")); + sRoamingAppDataDir, u"\\Macromedia\\Flash Player"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sLocalAppDataDir, NS_LITERAL_STRING("\\Macromedia")); + sLocalAppDataDir, u"\\Macromedia"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sLocalAppDataDir, - NS_LITERAL_STRING("\\Macromedia\\Flash Player")); + sLocalAppDataDir, u"\\Macromedia\\Flash Player"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sRoamingAppDataDir, NS_LITERAL_STRING("\\Adobe")); + sRoamingAppDataDir, u"\\Adobe"_ns); AddCachedDirRule(mPolicy, sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY, - sRoamingAppDataDir, - NS_LITERAL_STRING("\\Adobe\\Flash Player")); + sRoamingAppDataDir, u"\\Adobe\\Flash Player"_ns); } // Add the policy for the client side of a pipe. It is just a file diff --git a/services/crypto/component/IdentityCryptoService.cpp b/services/crypto/component/IdentityCryptoService.cpp index 64df4961752e..43dab9f1c7b1 100644 --- a/services/crypto/component/IdentityCryptoService.cpp +++ b/services/crypto/component/IdentityCryptoService.cpp @@ -40,8 +40,8 @@ void HexEncode(const SECItem* it, nsACString& result) { } } -#define DSA_KEY_TYPE_STRING (NS_LITERAL_CSTRING("DS160")) -#define RSA_KEY_TYPE_STRING (NS_LITERAL_CSTRING("RS256")) +#define DSA_KEY_TYPE_STRING ("DS160"_ns) +#define RSA_KEY_TYPE_STRING ("RS256"_ns) class KeyPair : public nsIIdentityKeyPair { public: diff --git a/startupcache/StartupCache.cpp b/startupcache/StartupCache.cpp index 7b74e09a97e4..a9580f3360db 100644 --- a/startupcache/StartupCache.cpp +++ b/startupcache/StartupCache.cpp @@ -185,14 +185,14 @@ nsresult StartupCache::Init() { return rv; } - rv = file->AppendNative(NS_LITERAL_CSTRING("startupCache")); + rv = file->AppendNative("startupCache"_ns); NS_ENSURE_SUCCESS(rv, rv); // Try to create the directory if it's not there yet rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777); if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) return rv; - rv = file->AppendNative(NS_LITERAL_CSTRING(STARTUP_CACHE_NAME)); + rv = file->AppendNative(nsLiteralCString(STARTUP_CACHE_NAME)); NS_ENSURE_SUCCESS(rv, rv); diff --git a/startupcache/test/TestStartupCache.cpp b/startupcache/test/TestStartupCache.cpp index dfe5049a75d8..b01ae2154b87 100644 --- a/startupcache/test/TestStartupCache.cpp +++ b/startupcache/test/TestStartupCache.cpp @@ -53,9 +53,9 @@ class TestStartupCache : public ::testing::Test { TestStartupCache::TestStartupCache() { NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mSCFile)); - mSCFile->AppendNative(NS_LITERAL_CSTRING("test-startupcache.tmp")); + mSCFile->AppendNative("test-startupcache.tmp"_ns); #ifdef XP_WIN - nsAutoString env(NS_LITERAL_STRING("MOZ_STARTUP_CACHE=")); + nsAutoString env(u"MOZ_STARTUP_CACHE="_ns); env.Append(mSCFile->NativePath()); _wputenv(env.get()); #else diff --git a/storage/TelemetryVFS.cpp b/storage/TelemetryVFS.cpp index f1a0f1c08992..bdb04c2474aa 100644 --- a/storage/TelemetryVFS.cpp +++ b/storage/TelemetryVFS.cpp @@ -556,7 +556,7 @@ int xDelete(sqlite3_vfs* vfs, const char* zName, int syncDir) { int rc; RefPtr quotaObject; - if (StringEndsWith(nsDependentCString(zName), NS_LITERAL_CSTRING("-wal"))) { + if (StringEndsWith(nsDependentCString(zName), "-wal"_ns)) { quotaObject = GetQuotaObjectFromName(zName); } diff --git a/storage/VacuumManager.cpp b/storage/VacuumManager.cpp index d184a08add77..e243276ae647 100644 --- a/storage/VacuumManager.cpp +++ b/storage/VacuumManager.cpp @@ -198,8 +198,7 @@ bool Vacuumer::execute() { NS_ENSURE_SUCCESS(rv, false); nsCOMPtr stmt; - rv = mDBConn->CreateAsyncStatement(NS_LITERAL_CSTRING("VACUUM"), - getter_AddRefs(stmt)); + rv = mDBConn->CreateAsyncStatement("VACUUM"_ns, getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, false); rv = stmt->ExecuteAsync(this, getter_AddRefs(ps)); NS_ENSURE_SUCCESS(rv, false); diff --git a/storage/mozStorageAsyncStatement.cpp b/storage/mozStorageAsyncStatement.cpp index adec04e8189d..ba050e9d333f 100644 --- a/storage/mozStorageAsyncStatement.cpp +++ b/storage/mozStorageAsyncStatement.cpp @@ -123,16 +123,16 @@ nsresult AsyncStatement::initialize(Connection* aDBConnection, aSQLStatement.BeginReading(start); aSQLStatement.EndReading(end); e = end; - while (::FindInReadable(NS_LITERAL_CSTRING(" LIKE"), start, e, c)) { + while (::FindInReadable(" LIKE"_ns, start, e, c)) { // We have a LIKE in here, so we perform our tests // FindInReadable moves the iterator, so we have to get a new one for // each test we perform. nsACString::const_iterator s1, s2, s3; s1 = s2 = s3 = start; - if (!(::FindInReadable(NS_LITERAL_CSTRING(" LIKE ?"), s1, end, c) || - ::FindInReadable(NS_LITERAL_CSTRING(" LIKE :"), s2, end, c) || - ::FindInReadable(NS_LITERAL_CSTRING(" LIKE @"), s3, end, c))) { + if (!(::FindInReadable(" LIKE ?"_ns, s1, end, c) || + ::FindInReadable(" LIKE :"_ns, s2, end, c) || + ::FindInReadable(" LIKE @"_ns, s3, end, c))) { // At this point, we didn't find a LIKE statement followed by ?, :, // or @, all of which are valid characters for binding a parameter. // We will warn the consumer that they may not be safely using LIKE. diff --git a/storage/mozStorageConnection.cpp b/storage/mozStorageConnection.cpp index c4c3be68e7dd..53984b2151cc 100644 --- a/storage/mozStorageConnection.cpp +++ b/storage/mozStorageConnection.cpp @@ -552,8 +552,7 @@ nsIEventTarget* Connection::getAsyncExecutionTarget() { NS_WARNING("Failed to create async thread."); return nullptr; } - mAsyncExecutionThread->SetNameForWakeupTelemetry( - NS_LITERAL_CSTRING("mozStorage (all)")); + mAsyncExecutionThread->SetNameForWakeupTelemetry("mozStorage (all)"_ns); } return mAsyncExecutionThread; @@ -745,15 +744,14 @@ nsresult Connection::initializeInternal() { // Set the synchronous PRAGMA, according to the preference. switch (Service::getSynchronousPref()) { case 2: - (void)ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = FULL;")); + (void)ExecuteSimpleSQL("PRAGMA synchronous = FULL;"_ns); break; case 0: - (void)ExecuteSimpleSQL(NS_LITERAL_CSTRING("PRAGMA synchronous = OFF;")); + (void)ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns); break; case 1: default: - (void)ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA synchronous = NORMAL;")); + (void)ExecuteSimpleSQL("PRAGMA synchronous = NORMAL;"_ns); break; } @@ -1443,8 +1441,7 @@ nsresult Connection::initializeClone(Connection* aClone, bool aReadOnly) { // Re-attach on-disk databases that were attached to the original connection. { nsCOMPtr stmt; - rv = CreateStatement(NS_LITERAL_CSTRING("PRAGMA database_list"), - getter_AddRefs(stmt)); + rv = CreateStatement("PRAGMA database_list"_ns, getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); bool hasResult = false; while (stmt && NS_SUCCEEDED(stmt->ExecuteStep(&hasResult)) && hasResult) { @@ -1456,12 +1453,10 @@ nsresult Connection::initializeClone(Connection* aClone, bool aReadOnly) { rv = stmt->GetUTF8String(2, path); if (NS_SUCCEEDED(rv) && !path.IsEmpty()) { nsCOMPtr attachStmt; - rv = aClone->CreateStatement( - NS_LITERAL_CSTRING("ATTACH DATABASE :path AS ") + name, - getter_AddRefs(attachStmt)); + rv = aClone->CreateStatement("ATTACH DATABASE :path AS "_ns + name, + getter_AddRefs(attachStmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = attachStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("path"), - path); + rv = attachStmt->BindUTF8StringByName("path"_ns, path); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = attachStmt->Execute(); MOZ_ASSERT(NS_SUCCEEDED(rv), @@ -1503,15 +1498,14 @@ nsresult Connection::initializeClone(Connection* aClone, bool aReadOnly) { // connections. Entities in `sqlite_temp_master` are only visible to the // connection that created them. if (!aReadOnly) { - rv = aClone->ExecuteSimpleSQL(NS_LITERAL_CSTRING("BEGIN TRANSACTION")); + rv = aClone->ExecuteSimpleSQL("BEGIN TRANSACTION"_ns); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr stmt; - rv = - CreateStatement(NS_LITERAL_CSTRING("SELECT sql FROM sqlite_temp_master " - "WHERE type IN ('table', 'view', " - "'index', 'trigger')"), - getter_AddRefs(stmt)); + rv = CreateStatement(nsLiteralCString("SELECT sql FROM sqlite_temp_master " + "WHERE type IN ('table', 'view', " + "'index', 'trigger')"), + getter_AddRefs(stmt)); // Propagate errors, because failing to copy triggers might cause schema // coherency issues when writing to the database from the cloned connection. NS_ENSURE_SUCCESS(rv, rv); @@ -1525,9 +1519,9 @@ nsresult Connection::initializeClone(Connection* aClone, bool aReadOnly) { // keyword. We need to add it back, or we'll recreate temporary entities // as persistent ones. `sqlite_temp_master` also holds `CREATE INDEX` // statements, but those don't need `TEMP` keywords. - if (StringBeginsWith(query, NS_LITERAL_CSTRING("CREATE TABLE ")) || - StringBeginsWith(query, NS_LITERAL_CSTRING("CREATE TRIGGER ")) || - StringBeginsWith(query, NS_LITERAL_CSTRING("CREATE VIEW "))) { + if (StringBeginsWith(query, "CREATE TABLE "_ns) || + StringBeginsWith(query, "CREATE TRIGGER "_ns) || + StringBeginsWith(query, "CREATE VIEW "_ns)) { query.Replace(0, 6, "CREATE TEMP"); } @@ -1535,7 +1529,7 @@ nsresult Connection::initializeClone(Connection* aClone, bool aReadOnly) { NS_ENSURE_SUCCESS(rv, rv); } - rv = aClone->ExecuteSimpleSQL(NS_LITERAL_CSTRING("COMMIT")); + rv = aClone->ExecuteSimpleSQL("COMMIT"_ns); NS_ENSURE_SUCCESS(rv, rv); } @@ -1706,8 +1700,7 @@ Connection::GetSchemaVersion(int32_t* _version) { } nsCOMPtr stmt; - (void)CreateStatement(NS_LITERAL_CSTRING("PRAGMA user_version"), - getter_AddRefs(stmt)); + (void)CreateStatement("PRAGMA user_version"_ns, getter_AddRefs(stmt)); NS_ENSURE_TRUE(stmt, NS_ERROR_OUT_OF_MEMORY); *_version = 0; @@ -1728,7 +1721,7 @@ Connection::SetSchemaVersion(int32_t aVersion) { return rv; } - nsAutoCString stmt(NS_LITERAL_CSTRING("PRAGMA user_version = ")); + nsAutoCString stmt("PRAGMA user_version = "_ns); stmt.AppendInt(aVersion); return ExecuteSimpleSQL(stmt); diff --git a/storage/mozStorageHelper.h b/storage/mozStorageHelper.h index 1fe492f758c8..d5d60e2b1e24 100644 --- a/storage/mozStorageHelper.h +++ b/storage/mozStorageHelper.h @@ -117,10 +117,10 @@ class mozStorageTransaction { nsresult rv; if (mAsyncCommit) { nsCOMPtr ps; - rv = mConnection->ExecuteSimpleSQLAsync(NS_LITERAL_CSTRING("COMMIT"), - nullptr, getter_AddRefs(ps)); + rv = mConnection->ExecuteSimpleSQLAsync("COMMIT"_ns, nullptr, + getter_AddRefs(ps)); } else { - rv = mConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("COMMIT")); + rv = mConnection->ExecuteSimpleSQL("COMMIT"_ns); } if (NS_SUCCEEDED(rv)) mHasTransaction = false; @@ -141,7 +141,7 @@ class mozStorageTransaction { // a busy error, so this handling can be removed. nsresult rv; do { - rv = mConnection->ExecuteSimpleSQL(NS_LITERAL_CSTRING("ROLLBACK")); + rv = mConnection->ExecuteSimpleSQL("ROLLBACK"_ns); if (rv == NS_ERROR_STORAGE_BUSY) (void)PR_Sleep(PR_INTERVAL_NO_WAIT); } while (rv == NS_ERROR_STORAGE_BUSY); diff --git a/storage/mozStorageService.cpp b/storage/mozStorageService.cpp index 92397c77de7d..1b6ee073bbce 100644 --- a/storage/mozStorageService.cpp +++ b/storage/mozStorageService.cpp @@ -131,24 +131,21 @@ Service::CollectReports(nsIHandleReportCallback* aHandleReport, stmtDesc, "Memory (approximate) used by all prepared statements used by " "connections to this database."); - ReportConn(aHandleReport, aData, conn, pathHead, - NS_LITERAL_CSTRING("stmt"), stmtDesc, + ReportConn(aHandleReport, aData, conn, pathHead, "stmt"_ns, stmtDesc, SQLITE_DBSTATUS_STMT_USED, &totalConnSize); NS_NAMED_LITERAL_CSTRING( cacheDesc, "Memory (approximate) used by all pager caches used by connections " "to this database."); - ReportConn(aHandleReport, aData, conn, pathHead, - NS_LITERAL_CSTRING("cache"), cacheDesc, + ReportConn(aHandleReport, aData, conn, pathHead, "cache"_ns, cacheDesc, SQLITE_DBSTATUS_CACHE_USED_SHARED, &totalConnSize); NS_NAMED_LITERAL_CSTRING( schemaDesc, "Memory (approximate) used to store the schema for all databases " "associated with connections to this database."); - ReportConn(aHandleReport, aData, conn, pathHead, - NS_LITERAL_CSTRING("schema"), schemaDesc, + ReportConn(aHandleReport, aData, conn, pathHead, "schema"_ns, schemaDesc, SQLITE_DBSTATUS_SCHEMA_USED, &totalConnSize); } @@ -516,10 +513,10 @@ Service::OpenAsyncDatabase(nsIVariant* aDatabaseStore, // Deal with options first: if (aOptions) { - rv = aOptions->GetPropertyAsBool(NS_LITERAL_STRING("readOnly"), &readOnly); + rv = aOptions->GetPropertyAsBool(u"readOnly"_ns, &readOnly); FAIL_IF_SET_BUT_INVALID(rv); - rv = aOptions->GetPropertyAsBool(NS_LITERAL_STRING("ignoreLockingMode"), + rv = aOptions->GetPropertyAsBool(u"ignoreLockingMode"_ns, &ignoreLockingMode); FAIL_IF_SET_BUT_INVALID(rv); // Specifying ignoreLockingMode will force use of the readOnly flag: @@ -527,12 +524,11 @@ Service::OpenAsyncDatabase(nsIVariant* aDatabaseStore, readOnly = true; } - rv = aOptions->GetPropertyAsBool(NS_LITERAL_STRING("shared"), &shared); + rv = aOptions->GetPropertyAsBool(u"shared"_ns, &shared); FAIL_IF_SET_BUT_INVALID(rv); // NB: we re-set to -1 if we don't have a storage file later on. - rv = aOptions->GetPropertyAsInt32(NS_LITERAL_STRING("growthIncrement"), - &growthIncrement); + rv = aOptions->GetPropertyAsInt32(u"growthIncrement"_ns, &growthIncrement); FAIL_IF_SET_BUT_INVALID(rv); } int flags = readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE; diff --git a/storage/mozStorageStatement.cpp b/storage/mozStorageStatement.cpp index 940b23576995..d857c4816402 100644 --- a/storage/mozStorageStatement.cpp +++ b/storage/mozStorageStatement.cpp @@ -153,16 +153,16 @@ nsresult Statement::initialize(Connection* aDBConnection, aSQLStatement.BeginReading(start); aSQLStatement.EndReading(end); e = end; - while (::FindInReadable(NS_LITERAL_CSTRING(" LIKE"), start, e, c)) { + while (::FindInReadable(" LIKE"_ns, start, e, c)) { // We have a LIKE in here, so we perform our tests // FindInReadable moves the iterator, so we have to get a new one for // each test we perform. nsACString::const_iterator s1, s2, s3; s1 = s2 = s3 = start; - if (!(::FindInReadable(NS_LITERAL_CSTRING(" LIKE ?"), s1, end, c) || - ::FindInReadable(NS_LITERAL_CSTRING(" LIKE :"), s2, end, c) || - ::FindInReadable(NS_LITERAL_CSTRING(" LIKE @"), s3, end, c))) { + if (!(::FindInReadable(" LIKE ?"_ns, s1, end, c) || + ::FindInReadable(" LIKE :"_ns, s2, end, c) || + ::FindInReadable(" LIKE @"_ns, s3, end, c))) { // At this point, we didn't find a LIKE statement followed by ?, :, // or @, all of which are valid characters for binding a parameter. // We will warn the consumer that they may not be safely using LIKE. diff --git a/storage/test/gtest/storage_test_harness.h b/storage/test/gtest/storage_test_harness.h index 589abeddad6f..9a6d37e691f2 100644 --- a/storage/test/gtest/storage_test_harness.h +++ b/storage/test/gtest/storage_test_harness.h @@ -69,7 +69,7 @@ already_AddRefed getDatabase( getter_AddRefs(dbFile)); NS_ASSERTION(dbFile, "The directory doesn't exists?!"); - rv = dbFile->Append(NS_LITERAL_STRING("storage_test_db.sqlite")); + rv = dbFile->Append(u"storage_test_db.sqlite"_ns); do_check_success(rv); } else { dbFile = aDBFile; @@ -314,8 +314,7 @@ already_AddRefed get_conn_async_thread(mozIStorageConnection* db) { // - statement with nothing to bind nsCOMPtr stmt; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT 1"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("SELECT 1"_ns, getter_AddRefs(stmt)); blocking_async_execute(stmt); stmt->Finalize(); diff --git a/storage/test/gtest/test_AsXXX_helpers.cpp b/storage/test/gtest/test_AsXXX_helpers.cpp index 1ff46ef8f289..2320b8383c75 100644 --- a/storage/test/gtest/test_AsXXX_helpers.cpp +++ b/storage/test/gtest/test_AsXXX_helpers.cpp @@ -56,8 +56,7 @@ TEST(storage_AsXXX_helpers, NULLFallback) nsCOMPtr db(getMemoryDatabase()); nsCOMPtr stmt; - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT NULL"), - getter_AddRefs(stmt)); + (void)db->CreateStatement("SELECT NULL"_ns, getter_AddRefs(stmt)); nsCOMPtr valueArray = do_QueryInterface(stmt); do_check_true(valueArray); @@ -99,8 +98,7 @@ TEST(storage_AsXXX_helpers, asyncNULLFallback) nsCOMPtr db(getMemoryDatabase()); nsCOMPtr stmt; - (void)db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT NULL"), - getter_AddRefs(stmt)); + (void)db->CreateAsyncStatement("SELECT NULL"_ns, getter_AddRefs(stmt)); nsCOMPtr pendingStmt; do_check_true( diff --git a/storage/test/gtest/test_asyncStatementExecution_transaction.cpp b/storage/test/gtest/test_asyncStatementExecution_transaction.cpp index f2570443ad50..0e7dec1e8a04 100644 --- a/storage/test/gtest/test_asyncStatementExecution_transaction.cpp +++ b/storage/test/gtest/test_asyncStatementExecution_transaction.cpp @@ -85,11 +85,11 @@ TEST(storage_asyncStatementExecution_transaction, MultipleAsyncReadStatements) // -- create statements and execute them nsCOMPtr stmt1; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + db->CreateAsyncStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + db->CreateAsyncStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt2)); nsTArray> stmts = { @@ -110,12 +110,10 @@ TEST(storage_asyncStatementExecution_transaction, MultipleReadStatements) // -- create statements and execute them nsCOMPtr stmt1; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), - getter_AddRefs(stmt1)); + db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), - getter_AddRefs(stmt2)); + db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt2)); nsTArray> stmts = { ToRefPtr(std::move(stmt1)), @@ -136,13 +134,12 @@ TEST(storage_asyncStatementExecution_transaction, // -- create statements and execute them nsCOMPtr stmt1; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + db->CreateAsyncStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt2)); + db->CreateAsyncStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt2)); nsTArray> stmts = { ToRefPtr(std::move(stmt1)), @@ -161,13 +158,11 @@ TEST(storage_asyncStatementExecution_transaction, MultipleReadWriteStatements) // -- create statements and execute them nsCOMPtr stmt1; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), - getter_AddRefs(stmt1)); + db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt2)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt2)); nsTArray> stmts = { ToRefPtr(std::move(stmt1)), @@ -187,14 +182,12 @@ TEST(storage_asyncStatementExecution_transaction, MultipleAsyncWriteStatements) // -- create statements and execute them nsCOMPtr stmt1; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test1 (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt1)); + db->CreateAsyncStatement("CREATE TABLE test1 (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt2)); + db->CreateAsyncStatement("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt2)); nsTArray> stmts = { ToRefPtr(std::move(stmt1)), @@ -214,14 +207,12 @@ TEST(storage_asyncStatementExecution_transaction, MultipleWriteStatements) // -- create statements and execute them nsCOMPtr stmt1; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test1 (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt1)); + db->CreateStatement("CREATE TABLE test1 (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt1)); nsCOMPtr stmt2; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt2)); + db->CreateStatement("CREATE TABLE test2 (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt2)); nsTArray> stmts = { ToRefPtr(std::move(stmt1)), @@ -241,7 +232,7 @@ TEST(storage_asyncStatementExecution_transaction, SingleAsyncReadStatement) // -- create statements and execute them nsCOMPtr stmt; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + db->CreateAsyncStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt)); nsTArray> stmts = { @@ -261,8 +252,7 @@ TEST(storage_asyncStatementExecution_transaction, SingleReadStatement) // -- create statements and execute them nsCOMPtr stmt; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), - getter_AddRefs(stmt)); + db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt)); nsTArray> stmts = { ToRefPtr(std::move(stmt)), @@ -281,9 +271,8 @@ TEST(storage_asyncStatementExecution_transaction, SingleAsyncWriteStatement) // -- create statements and execute them nsCOMPtr stmt; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); nsTArray> stmts = { ToRefPtr(std::move(stmt)), @@ -301,9 +290,8 @@ TEST(storage_asyncStatementExecution_transaction, SingleWriteStatement) // -- create statements and execute them nsCOMPtr stmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); nsTArray> stmts = { ToRefPtr(std::move(stmt)), @@ -323,9 +311,8 @@ TEST(storage_asyncStatementExecution_transaction, // -- create statements and execute them nsCOMPtr stmt; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("SELECT :param FROM sqlite_master"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("SELECT :param FROM sqlite_master"_ns, + getter_AddRefs(stmt)); // -- bind multiple BindingParams nsCOMPtr paramsArray; @@ -333,7 +320,7 @@ TEST(storage_asyncStatementExecution_transaction, for (int32_t i = 0; i < 2; i++) { nsCOMPtr params; paramsArray->NewBindingParams(getter_AddRefs(params)); - params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1); + params->BindInt32ByName("param"_ns, 1); paramsArray->AddParams(params); } stmt->BindParameters(paramsArray); @@ -356,7 +343,7 @@ TEST(storage_asyncStatementExecution_transaction, MultipleParamsReadStatement) // -- create statements and execute them nsCOMPtr stmt; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT :param FROM sqlite_master"), + db->CreateStatement("SELECT :param FROM sqlite_master"_ns, getter_AddRefs(stmt)); // -- bind multiple BindingParams @@ -365,7 +352,7 @@ TEST(storage_asyncStatementExecution_transaction, MultipleParamsReadStatement) for (int32_t i = 0; i < 2; i++) { nsCOMPtr params; paramsArray->NewBindingParams(getter_AddRefs(params)); - params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1); + params->BindInt32ByName("param"_ns, 1); paramsArray->AddParams(params); } stmt->BindParameters(paramsArray); @@ -389,17 +376,15 @@ TEST(storage_asyncStatementExecution_transaction, // -- create a table for writes nsCOMPtr tableStmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(tableStmt)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(tableStmt)); tableStmt->Execute(); tableStmt->Finalize(); // -- create statements and execute them nsCOMPtr stmt; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("DELETE FROM test WHERE id = :param"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("DELETE FROM test WHERE id = :param"_ns, + getter_AddRefs(stmt)); // -- bind multiple BindingParams nsCOMPtr paramsArray; @@ -407,7 +392,7 @@ TEST(storage_asyncStatementExecution_transaction, for (int32_t i = 0; i < 2; i++) { nsCOMPtr params; paramsArray->NewBindingParams(getter_AddRefs(params)); - params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1); + params->BindInt32ByName("param"_ns, 1); paramsArray->AddParams(params); } stmt->BindParameters(paramsArray); @@ -430,15 +415,14 @@ TEST(storage_asyncStatementExecution_transaction, MultipleParamsWriteStatement) // -- create a table for writes nsCOMPtr tableStmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(tableStmt)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(tableStmt)); tableStmt->Execute(); tableStmt->Finalize(); // -- create statements and execute them nsCOMPtr stmt; - db->CreateStatement(NS_LITERAL_CSTRING("DELETE FROM test WHERE id = :param"), + db->CreateStatement("DELETE FROM test WHERE id = :param"_ns, getter_AddRefs(stmt)); // -- bind multiple BindingParams @@ -447,7 +431,7 @@ TEST(storage_asyncStatementExecution_transaction, MultipleParamsWriteStatement) for (int32_t i = 0; i < 2; i++) { nsCOMPtr params; paramsArray->NewBindingParams(getter_AddRefs(params)); - params->BindInt32ByName(NS_LITERAL_CSTRING("param"), 1); + params->BindInt32ByName("param"_ns, 1); paramsArray->AddParams(params); } stmt->BindParameters(paramsArray); diff --git a/storage/test/gtest/test_async_callbacks_with_spun_event_loops.cpp b/storage/test/gtest/test_async_callbacks_with_spun_event_loops.cpp index 30ae7e491e8c..bd437b61ecd3 100644 --- a/storage/test/gtest/test_async_callbacks_with_spun_event_loops.cpp +++ b/storage/test/gtest/test_async_callbacks_with_spun_event_loops.cpp @@ -95,13 +95,12 @@ TEST(storage_async_callbacks_with_spun_event_loops, // Create a test table and populate it. nsCOMPtr stmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); stmt->Execute(); stmt->Finalize(); - db->CreateStatement(NS_LITERAL_CSTRING("INSERT INTO test (id) VALUES (?)"), + db->CreateStatement("INSERT INTO test (id) VALUES (?)"_ns, getter_AddRefs(stmt)); for (int32_t i = 0; i < 30; ++i) { stmt->BindInt32ByIndex(0, i); @@ -110,8 +109,7 @@ TEST(storage_async_callbacks_with_spun_event_loops, } stmt->Finalize(); - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM test"), - getter_AddRefs(stmt)); + db->CreateStatement("SELECT * FROM test"_ns, getter_AddRefs(stmt)); nsCOMPtr ps; do_check_success( stmt->ExecuteAsync(new UnownedCallback(db), getter_AddRefs(ps))); @@ -126,19 +124,18 @@ TEST(storage_async_callbacks_with_spun_event_loops, SpinEventsLoopInHandleError) // Create a test table and populate it. nsCOMPtr stmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); stmt->Execute(); stmt->Finalize(); - db->CreateStatement(NS_LITERAL_CSTRING("INSERT INTO test (id) VALUES (1)"), + db->CreateStatement("INSERT INTO test (id) VALUES (1)"_ns, getter_AddRefs(stmt)); stmt->Execute(); stmt->Finalize(); // This will cause a constraint error. - db->CreateStatement(NS_LITERAL_CSTRING("INSERT INTO test (id) VALUES (1)"), + db->CreateStatement("INSERT INTO test (id) VALUES (1)"_ns, getter_AddRefs(stmt)); nsCOMPtr ps; do_check_success( diff --git a/storage/test/gtest/test_binding_params.cpp b/storage/test/gtest/test_binding_params.cpp index aacdec8af585..7309de9bd8c3 100644 --- a/storage/test/gtest/test_binding_params.cpp +++ b/storage/test/gtest/test_binding_params.cpp @@ -20,16 +20,13 @@ TEST(storage_binding_params, ASCIIString) nsCOMPtr db(getMemoryDatabase()); // Create table with a single string column. - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (str STRING)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (str STRING)"_ns); // Create statements to INSERT and SELECT the string. nsCOMPtr insert, select; - (void)db->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO test (str) VALUES (?1)"), - getter_AddRefs(insert)); - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT str FROM test"), - getter_AddRefs(select)); + (void)db->CreateStatement("INSERT INTO test (str) VALUES (?1)"_ns, + getter_AddRefs(insert)); + (void)db->CreateStatement("SELECT str FROM test"_ns, getter_AddRefs(select)); // Roundtrip a string through the table, and ensure it comes out as expected. nsAutoCString inserted("I'm an ASCII string"); @@ -52,7 +49,7 @@ TEST(storage_binding_params, ASCIIString) do_check_true(result == inserted); - (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test")); + (void)db->ExecuteSimpleSQL("DELETE FROM test"_ns); } TEST(storage_binding_params, CString) @@ -60,16 +57,13 @@ TEST(storage_binding_params, CString) nsCOMPtr db(getMemoryDatabase()); // Create table with a single string column. - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (str STRING)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (str STRING)"_ns); // Create statements to INSERT and SELECT the string. nsCOMPtr insert, select; - (void)db->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO test (str) VALUES (?1)"), - getter_AddRefs(insert)); - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT str FROM test"), - getter_AddRefs(select)); + (void)db->CreateStatement("INSERT INTO test (str) VALUES (?1)"_ns, + getter_AddRefs(insert)); + (void)db->CreateStatement("SELECT str FROM test"_ns, getter_AddRefs(select)); // Roundtrip a string through the table, and ensure it comes out as expected. static const char sCharArray[] = @@ -96,7 +90,7 @@ TEST(storage_binding_params, CString) do_check_true(result == inserted); } - (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test")); + (void)db->ExecuteSimpleSQL("DELETE FROM test"_ns); } TEST(storage_binding_params, UTFStrings) @@ -104,16 +98,13 @@ TEST(storage_binding_params, UTFStrings) nsCOMPtr db(getMemoryDatabase()); // Create table with a single string column. - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (str STRING)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (str STRING)"_ns); // Create statements to INSERT and SELECT the string. nsCOMPtr insert, select; - (void)db->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO test (str) VALUES (?1)"), - getter_AddRefs(insert)); - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT str FROM test"), - getter_AddRefs(select)); + (void)db->CreateStatement("INSERT INTO test (str) VALUES (?1)"_ns, + getter_AddRefs(insert)); + (void)db->CreateStatement("SELECT str FROM test"_ns, getter_AddRefs(select)); // Roundtrip a UTF8 string through the table, using UTF8 input and output. static const char sCharArray[] = R"(I'm a ûüâäç UTF8 string!)"; @@ -154,7 +145,7 @@ TEST(storage_binding_params, UTFStrings) do_check_true(result == insertedUTF16); } - (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test")); + (void)db->ExecuteSimpleSQL("DELETE FROM test"_ns); // Roundtrip the same string using UTF16 input and UTF8 output. { @@ -190,5 +181,5 @@ TEST(storage_binding_params, UTFStrings) do_check_true(result == insertedUTF16); } - (void)db->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM test")); + (void)db->ExecuteSimpleSQL("DELETE FROM test"_ns); } diff --git a/storage/test/gtest/test_spinningSynchronousClose.cpp b/storage/test/gtest/test_spinningSynchronousClose.cpp index c7e0234361ae..8746d0018a32 100644 --- a/storage/test/gtest/test_spinningSynchronousClose.cpp +++ b/storage/test/gtest/test_spinningSynchronousClose.cpp @@ -38,8 +38,7 @@ TEST(storage_spinningSynchronousClose, CloseOnAsync) // Run an async statement. nsCOMPtr stmt; do_check_success(db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt))); + "CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, getter_AddRefs(stmt))); nsCOMPtr p; do_check_success(stmt->ExecuteAsync(nullptr, getter_AddRefs(p))); do_check_success(stmt->Finalize()); @@ -58,8 +57,7 @@ TEST(storage_spinningSynchronousClose, spinningSynchronousCloseOnAsync) // Run an async statement. nsCOMPtr stmt; do_check_success(db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt))); + "CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, getter_AddRefs(stmt))); nsCOMPtr p; do_check_success(stmt->ExecuteAsync(nullptr, getter_AddRefs(p))); do_check_success(stmt->Finalize()); diff --git a/storage/test/gtest/test_statement_scoper.cpp b/storage/test/gtest/test_statement_scoper.cpp index 903d0e0b4af2..3327b0ff6b74 100644 --- a/storage/test/gtest/test_statement_scoper.cpp +++ b/storage/test/gtest/test_statement_scoper.cpp @@ -17,11 +17,10 @@ TEST(storage_statement_scoper, automatic_reset) nsCOMPtr db(getMemoryDatabase()); // Need to create a table to populate sqlite_master with an entry. - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); nsCOMPtr stmt; - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + (void)db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt)); // Reality check - make sure we start off in the right state. @@ -53,11 +52,10 @@ TEST(storage_statement_scoper, Abandon) nsCOMPtr db(getMemoryDatabase()); // Need to create a table to populate sqlite_master with an entry. - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); nsCOMPtr stmt; - (void)db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM sqlite_master"), + (void)db->CreateStatement("SELECT * FROM sqlite_master"_ns, getter_AddRefs(stmt)); // Reality check - make sure we start off in the right state. diff --git a/storage/test/gtest/test_transaction_helper.cpp b/storage/test/gtest/test_transaction_helper.cpp index 9aba19ced6b3..743b06731d01 100644 --- a/storage/test/gtest/test_transaction_helper.cpp +++ b/storage/test/gtest/test_transaction_helper.cpp @@ -29,14 +29,13 @@ TEST(storage_transaction_helper, Commit) { mozStorageTransaction transaction(db, false); do_check_true(has_transaction(db)); - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); (void)transaction.Commit(); } do_check_false(has_transaction(db)); bool exists = false; - (void)db->TableExists(NS_LITERAL_CSTRING("test"), &exists); + (void)db->TableExists("test"_ns, &exists); do_check_true(exists); } @@ -49,14 +48,13 @@ TEST(storage_transaction_helper, Rollback) { mozStorageTransaction transaction(db, true); do_check_true(has_transaction(db)); - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); (void)transaction.Rollback(); } do_check_false(has_transaction(db)); bool exists = true; - (void)db->TableExists(NS_LITERAL_CSTRING("test"), &exists); + (void)db->TableExists("test"_ns, &exists); do_check_false(exists); } @@ -69,13 +67,12 @@ TEST(storage_transaction_helper, AutoCommit) { mozStorageTransaction transaction(db, true); do_check_true(has_transaction(db)); - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); } do_check_false(has_transaction(db)); bool exists = false; - (void)db->TableExists(NS_LITERAL_CSTRING("test"), &exists); + (void)db->TableExists("test"_ns, &exists); do_check_true(exists); } @@ -89,13 +86,12 @@ TEST(storage_transaction_helper, AutoRollback) { mozStorageTransaction transaction(db, false); do_check_true(has_transaction(db)); - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); } do_check_false(has_transaction(db)); bool exists = true; - (void)db->TableExists(NS_LITERAL_CSTRING("test"), &exists); + (void)db->TableExists("test"_ns, &exists); do_check_false(exists); } @@ -123,8 +119,7 @@ TEST(storage_transaction_helper, async_Commit) mozStorageTransaction transaction( db, false, mozIStorageConnection::TRANSACTION_DEFERRED, true); do_check_true(has_transaction(db)); - (void)db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)")); + (void)db->ExecuteSimpleSQL("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns); (void)transaction.Commit(); } do_check_true(has_transaction(db)); @@ -134,13 +129,12 @@ TEST(storage_transaction_helper, async_Commit) // Ensure the transaction has done its job by enqueueing an async execution. nsCOMPtr stmt; - (void)db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT NULL"), - getter_AddRefs(stmt)); + (void)db->CreateAsyncStatement("SELECT NULL"_ns, getter_AddRefs(stmt)); blocking_async_execute(stmt); stmt->Finalize(); do_check_false(has_transaction(db)); bool exists = false; - (void)db->TableExists(NS_LITERAL_CSTRING("test"), &exists); + (void)db->TableExists("test"_ns, &exists); do_check_true(exists); blocking_async_close(db); diff --git a/storage/test/gtest/test_true_async.cpp b/storage/test/gtest/test_true_async.cpp index 1e0c33326fe8..3b54b73b3a28 100644 --- a/storage/test/gtest/test_true_async.cpp +++ b/storage/test/gtest/test_true_async.cpp @@ -20,31 +20,28 @@ TEST(storage_true_async, TrueAsyncStatement) // - statement with nothing to bind nsCOMPtr stmt; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); blocking_async_execute(stmt); stmt->Finalize(); do_check_false(mutex_used_on_watched_thread); // - statement with something to bind ordinally - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("INSERT INTO test (id) VALUES (?)"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("INSERT INTO test (id) VALUES (?)"_ns, + getter_AddRefs(stmt)); stmt->BindInt32ByIndex(0, 1); blocking_async_execute(stmt); stmt->Finalize(); do_check_false(mutex_used_on_watched_thread); // - statement with something to bind by name - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("INSERT INTO test (id) VALUES (:id)"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("INSERT INTO test (id) VALUES (:id)"_ns, + getter_AddRefs(stmt)); nsCOMPtr paramsArray; stmt->NewBindingParamsArray(getter_AddRefs(paramsArray)); nsCOMPtr params; paramsArray->NewBindingParams(getter_AddRefs(params)); - params->BindInt32ByName(NS_LITERAL_CSTRING("id"), 2); + params->BindInt32ByName("id"_ns, 2); paramsArray->AddParams(params); params = nullptr; stmt->BindParameters(paramsArray); @@ -56,8 +53,7 @@ TEST(storage_true_async, TrueAsyncStatement) // - now, make sure creating a sync statement does trigger our guard. // (If this doesn't happen, our test is bunk and it's important to know that.) nsCOMPtr syncStmt; - db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM test"), - getter_AddRefs(syncStmt)); + db->CreateStatement("SELECT * FROM test"_ns, getter_AddRefs(syncStmt)); syncStmt->Finalize(); do_check_true(mutex_used_on_watched_thread); @@ -83,7 +79,7 @@ TEST(storage_true_async, AsyncCancellation) // - async nsCOMPtr asyncStmt; db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE asyncTable (id INTEGER PRIMARY KEY)"), + "CREATE TABLE asyncTable (id INTEGER PRIMARY KEY)"_ns, getter_AddRefs(asyncStmt)); RefPtr asyncSpin(new AsyncStatementSpinner()); @@ -94,9 +90,8 @@ TEST(storage_true_async, AsyncCancellation) // - sync nsCOMPtr syncStmt; - db->CreateStatement( - NS_LITERAL_CSTRING("CREATE TABLE syncTable (id INTEGER PRIMARY KEY)"), - getter_AddRefs(syncStmt)); + db->CreateStatement("CREATE TABLE syncTable (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(syncStmt)); RefPtr syncSpin(new AsyncStatementSpinner()); nsCOMPtr syncPend; @@ -119,10 +114,10 @@ TEST(storage_true_async, AsyncCancellation) // -- verify that neither statement constructed their tables nsresult rv; bool exists; - rv = db->TableExists(NS_LITERAL_CSTRING("asyncTable"), &exists); + rv = db->TableExists("asyncTable"_ns, &exists); do_check_true(rv == NS_OK); do_check_false(exists); - rv = db->TableExists(NS_LITERAL_CSTRING("syncTable"), &exists); + rv = db->TableExists("syncTable"_ns, &exists); do_check_true(rv == NS_OK); do_check_false(exists); @@ -147,9 +142,8 @@ TEST(storage_true_async, AsyncDestructorFinalizesOnAsyncThread) // -- create an async statement nsCOMPtr stmt; - db->CreateAsyncStatement( - NS_LITERAL_CSTRING("CREATE TABLE test (id INTEGER PRIMARY KEY)"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("CREATE TABLE test (id INTEGER PRIMARY KEY)"_ns, + getter_AddRefs(stmt)); // -- execute it so it gets a sqlite3_stmt that needs to be finalized blocking_async_execute(stmt); diff --git a/storage/test/gtest/test_unlock_notify.cpp b/storage/test/gtest/test_unlock_notify.cpp index 857dbdee84dd..c168b2cbef37 100644 --- a/storage/test/gtest/test_unlock_notify.cpp +++ b/storage/test/gtest/test_unlock_notify.cpp @@ -121,17 +121,15 @@ void setup() { nsCOMPtr db(getDatabase()); // Create and populate a dummy table. - nsresult rv = db->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = db->ExecuteSimpleSQL(nsLiteralCString( "CREATE TABLE test (id INTEGER PRIMARY KEY, data STRING)")); do_check_success(rv); - rv = db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO test (data) VALUES ('foo')")); + rv = db->ExecuteSimpleSQL("INSERT INTO test (data) VALUES ('foo')"_ns); do_check_success(rv); - rv = db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO test (data) VALUES ('bar')")); + rv = db->ExecuteSimpleSQL("INSERT INTO test (data) VALUES ('bar')"_ns); do_check_success(rv); - rv = db->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("CREATE UNIQUE INDEX unique_data ON test (data)")); + rv = + db->ExecuteSimpleSQL("CREATE UNIQUE INDEX unique_data ON test (data)"_ns); do_check_success(rv); } @@ -142,8 +140,7 @@ void test_step_locked_does_not_block_main_thread() { // step and not prepare. nsCOMPtr stmt; nsresult rv = db->CreateStatement( - NS_LITERAL_CSTRING("INSERT INTO test (data) VALUES ('test1')"), - getter_AddRefs(stmt)); + "INSERT INTO test (data) VALUES ('test1')"_ns, getter_AddRefs(stmt)); do_check_success(rv); nsCOMPtr dbFile; @@ -174,8 +171,8 @@ void test_drop_index_does_not_loop() { // Need to prepare our statement ahead of time so we make sure to only test // step and not prepare. nsCOMPtr stmt; - nsresult rv = db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM test"), - getter_AddRefs(stmt)); + nsresult rv = + db->CreateStatement("SELECT * FROM test"_ns, getter_AddRefs(stmt)); do_check_success(rv); RefPtr tester = @@ -204,8 +201,8 @@ void test_drop_table_does_not_loop() { // Need to prepare our statement ahead of time so we make sure to only test // step and not prepare. nsCOMPtr stmt; - nsresult rv = db->CreateStatement(NS_LITERAL_CSTRING("SELECT * FROM test"), - getter_AddRefs(stmt)); + nsresult rv = + db->CreateStatement("SELECT * FROM test"_ns, getter_AddRefs(stmt)); do_check_success(rv); RefPtr tester(new DatabaseTester(db, "DROP TABLE test")); diff --git a/toolkit/components/alerts/nsXULAlerts.cpp b/toolkit/components/alerts/nsXULAlerts.cpp index 31b46793239b..af7f486ea1ac 100644 --- a/toolkit/components/alerts/nsXULAlerts.cpp +++ b/toolkit/components/alerts/nsXULAlerts.cpp @@ -396,7 +396,7 @@ nsXULAlerts::CloseAlert(const nsAString& aAlertName, nsIPrincipal* aPrincipal) { mozIDOMWindowProxy* alert = mNamedWindows.GetWeak(aAlertName); if (nsCOMPtr domWindow = nsPIDOMWindowOuter::From(alert)) { - domWindow->DispatchCustomEvent(NS_LITERAL_STRING("XULAlertClose"), + domWindow->DispatchCustomEvent(u"XULAlertClose"_ns, ChromeOnlyDispatch::eYes); } return NS_OK; diff --git a/toolkit/components/antitracking/AntiTrackingLog.h b/toolkit/components/antitracking/AntiTrackingLog.h index df147625931d..09d4828c44a0 100644 --- a/toolkit/components/antitracking/AntiTrackingLog.h +++ b/toolkit/components/antitracking/AntiTrackingLog.h @@ -20,7 +20,7 @@ static const nsCString::size_type sMaxSpecLength = 128; #define LOG_SPEC(format, uri) \ PR_BEGIN_MACRO \ if (MOZ_LOG_TEST(gAntiTrackingLog, mozilla::LogLevel::Debug)) { \ - nsAutoCString _specStr(NS_LITERAL_CSTRING("(null)")); \ + nsAutoCString _specStr("(null)"_ns); \ if (uri) { \ _specStr = (uri)->GetSpecOrDefault(); \ } \ @@ -33,13 +33,13 @@ static const nsCString::size_type sMaxSpecLength = 128; #define LOG_SPEC2(format, uri1, uri2) \ PR_BEGIN_MACRO \ if (MOZ_LOG_TEST(gAntiTrackingLog, mozilla::LogLevel::Debug)) { \ - nsAutoCString _specStr1(NS_LITERAL_CSTRING("(null)")); \ + nsAutoCString _specStr1("(null)"_ns); \ if (uri1) { \ _specStr1 = (uri1)->GetSpecOrDefault(); \ } \ _specStr1.Truncate(std::min(_specStr1.Length(), sMaxSpecLength)); \ const char* _spec1 = _specStr1.get(); \ - nsAutoCString _specStr2(NS_LITERAL_CSTRING("(null)")); \ + nsAutoCString _specStr2("(null)"_ns); \ if (uri2) { \ _specStr2 = (uri2)->GetSpecOrDefault(); \ } \ @@ -52,7 +52,7 @@ static const nsCString::size_type sMaxSpecLength = 128; #define LOG_PRIN(format, principal) \ PR_BEGIN_MACRO \ if (MOZ_LOG_TEST(gAntiTrackingLog, mozilla::LogLevel::Debug)) { \ - nsAutoCString _specStr(NS_LITERAL_CSTRING("(null)")); \ + nsAutoCString _specStr("(null)"_ns); \ if (principal) { \ (principal)->GetAsciiSpec(_specStr); \ } \ diff --git a/toolkit/components/antitracking/AntiTrackingUtils.cpp b/toolkit/components/antitracking/AntiTrackingUtils.cpp index 2962cddf448e..03a9ba1b47a0 100644 --- a/toolkit/components/antitracking/AntiTrackingUtils.cpp +++ b/toolkit/components/antitracking/AntiTrackingUtils.cpp @@ -93,7 +93,7 @@ void AntiTrackingUtils::CreateStoragePermissionKey( MOZ_ASSERT(aPermissionKey.IsEmpty()); static const nsLiteralCString prefix = - NS_LITERAL_CSTRING(ANTITRACKING_PERM_KEY "^"); + nsLiteralCString(ANTITRACKING_PERM_KEY "^"); aPermissionKey.SetCapacity(prefix.Length() + aTrackingOrigin.Length()); aPermissionKey.Append(prefix); @@ -625,10 +625,10 @@ nsCString AntiTrackingUtils::GrantedReasonToString( ContentBlockingNotifier::StorageAccessPermissionGrantedReason aReason) { switch (aReason) { case ContentBlockingNotifier::eOpener: - return NS_LITERAL_CSTRING("opener"); + return "opener"_ns; case ContentBlockingNotifier::eOpenerAfterUserInteraction: - return NS_LITERAL_CSTRING("user interaction"); + return "user interaction"_ns; default: - return NS_LITERAL_CSTRING("stroage access API"); + return "stroage access API"_ns; } } diff --git a/toolkit/components/antitracking/ContentBlocking.cpp b/toolkit/components/antitracking/ContentBlocking.cpp index deaf7f773f3b..efbdb73b13fb 100644 --- a/toolkit/components/antitracking/ContentBlocking.cpp +++ b/toolkit/components/antitracking/ContentBlocking.cpp @@ -1227,7 +1227,7 @@ bool ContentBlocking::ShouldAllowAccessFor( PermissionManager* permManager = PermissionManager::GetInstance(); if (permManager) { Unused << NS_WARN_IF(NS_FAILED(permManager->TestPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("cookie"), &access))); + aPrincipal, "cookie"_ns, &access))); } } diff --git a/toolkit/components/antitracking/ContentBlockingAllowList.cpp b/toolkit/components/antitracking/ContentBlockingAllowList.cpp index 3b3a2a630380..2abffac7b1cc 100644 --- a/toolkit/components/antitracking/ContentBlockingAllowList.cpp +++ b/toolkit/components/antitracking/ContentBlockingAllowList.cpp @@ -103,8 +103,7 @@ nsresult ContentBlockingAllowList::Check( // Check both the normal mode and private browsing mode user override // permissions. std::pair types[] = { - {NS_LITERAL_CSTRING("trackingprotection"), false}, - {NS_LITERAL_CSTRING("trackingprotection-pb"), true}}; + {"trackingprotection"_ns, false}, {"trackingprotection-pb"_ns, true}}; for (const auto& type : types) { if (aIsPrivateBrowsing != type.second) { @@ -155,7 +154,7 @@ nsresult ContentBlockingAllowList::Check( // Take the host/port portion so we can allowlist by site. Also ignore the // scheme, since users who put sites on the allowlist probably don't expect // allowlisting to depend on scheme. - nsAutoCString escaped(NS_LITERAL_CSTRING("https://")); + nsAutoCString escaped("https://"_ns); nsAutoCString temp; nsresult rv = aDocumentPrincipal->GetHostPort(temp); // view-source URIs will be handled by the next block. @@ -200,7 +199,7 @@ nsresult ContentBlockingAllowList::Check( // Take the host/port portion so we can allowlist by site. Also ignore the // scheme, since users who put sites on the allowlist probably don't expect // allowlisting to depend on scheme. - nsAutoCString escaped(NS_LITERAL_CSTRING("https://")); + nsAutoCString escaped("https://"_ns); nsAutoCString temp; nsresult rv = aURIBeingLoaded->GetHostPort(temp); // view-source URIs will be handled by the next block. diff --git a/toolkit/components/antitracking/ContentBlockingNotifier.cpp b/toolkit/components/antitracking/ContentBlockingNotifier.cpp index 3c48539f9cae..7b108143d615 100644 --- a/toolkit/components/antitracking/ContentBlockingNotifier.cpp +++ b/toolkit/components/antitracking/ContentBlockingNotifier.cpp @@ -147,28 +147,28 @@ void ReportBlockingToConsole(uint64_t aWindowID, nsIURI* aURI, case uint32_t( nsIWebProgressListener::STATE_COOKIES_BLOCKED_BY_PERMISSION): message = "CookieBlockedByPermission"; - category = NS_LITERAL_CSTRING("cookieBlockedPermission"); + category = "cookieBlockedPermission"_ns; break; case uint32_t(nsIWebProgressListener::STATE_COOKIES_BLOCKED_TRACKER): message = "CookieBlockedTracker"; - category = NS_LITERAL_CSTRING("cookieBlockedTracker"); + category = "cookieBlockedTracker"_ns; break; case uint32_t(nsIWebProgressListener::STATE_COOKIES_BLOCKED_ALL): message = "CookieBlockedAll"; - category = NS_LITERAL_CSTRING("cookieBlockedAll"); + category = "cookieBlockedAll"_ns; break; case uint32_t(nsIWebProgressListener::STATE_COOKIES_BLOCKED_FOREIGN): message = "CookieBlockedForeign"; - category = NS_LITERAL_CSTRING("cookieBlockedForeign"); + category = "cookieBlockedForeign"_ns; break; case uint32_t( nsIWebProgressListener::STATE_COOKIES_PARTITIONED_FOREIGN): message = "CookiePartitionedForeign"; - category = NS_LITERAL_CSTRING("cookiePartitionedForeign"); + category = "cookiePartitionedForeign"_ns; break; default: diff --git a/toolkit/components/antitracking/ContentBlockingNotifier.h b/toolkit/components/antitracking/ContentBlockingNotifier.h index 5aa129ad6306..9aa3b80bc4f7 100644 --- a/toolkit/components/antitracking/ContentBlockingNotifier.h +++ b/toolkit/components/antitracking/ContentBlockingNotifier.h @@ -10,7 +10,7 @@ #include "nsStringFwd.h" #include "mozilla/Maybe.h" -#define ANTITRACKING_CONSOLE_CATEGORY NS_LITERAL_CSTRING("Content Blocking") +#define ANTITRACKING_CONSOLE_CATEGORY "Content Blocking"_ns class nsIChannel; class nsPIDOMWindowInner; diff --git a/toolkit/components/antitracking/ContentBlockingUserInteraction.h b/toolkit/components/antitracking/ContentBlockingUserInteraction.h index 31d105702bac..503990ae82a0 100644 --- a/toolkit/components/antitracking/ContentBlockingUserInteraction.h +++ b/toolkit/components/antitracking/ContentBlockingUserInteraction.h @@ -7,7 +7,7 @@ #ifndef mozilla_contentblockinguserinteraction_h #define mozilla_contentblockinguserinteraction_h -#define USER_INTERACTION_PERM NS_LITERAL_CSTRING("storageAccessAPI") +#define USER_INTERACTION_PERM "storageAccessAPI"_ns class nsIPrincipal; diff --git a/toolkit/components/antitracking/DynamicFpiRedirectHeuristic.cpp b/toolkit/components/antitracking/DynamicFpiRedirectHeuristic.cpp index c31db74908ff..200b913a93d5 100644 --- a/toolkit/components/antitracking/DynamicFpiRedirectHeuristic.cpp +++ b/toolkit/components/antitracking/DynamicFpiRedirectHeuristic.cpp @@ -148,10 +148,10 @@ void AddConsoleReport(nsIChannel* aNewChannel, nsIURI* aNewURI, AutoTArray params = {NS_ConvertUTF8toUTF16(aNewOrigin), NS_ConvertUTF8toUTF16(aOldOrigin)}; - httpChannel->AddConsoleReport( - nsIScriptError::warningFlag, ANTITRACKING_CONSOLE_CATEGORY, - nsContentUtils::eNECKO_PROPERTIES, uri, 0, 0, - NS_LITERAL_CSTRING("CookieAllowedForFpiByHeuristic"), params); + httpChannel->AddConsoleReport(nsIScriptError::warningFlag, + ANTITRACKING_CONSOLE_CATEGORY, + nsContentUtils::eNECKO_PROPERTIES, uri, 0, 0, + "CookieAllowedForFpiByHeuristic"_ns, params); } bool ShouldRedirectHeuristicApplyTrackingResource(nsIChannel* aOldChannel, diff --git a/toolkit/components/antitracking/RejectForeignAllowList.cpp b/toolkit/components/antitracking/RejectForeignAllowList.cpp index 8de83e2f2f99..3745391491f2 100644 --- a/toolkit/components/antitracking/RejectForeignAllowList.cpp +++ b/toolkit/components/antitracking/RejectForeignAllowList.cpp @@ -10,9 +10,8 @@ #include "mozilla/StaticPtr.h" #include "nsNetUtil.h" -#define REJECTFOREIGNALLOWLIST_PREF \ - NS_LITERAL_CSTRING("privacy.rejectForeign.allowList") -#define REJECTFOREIGNALLOWLIST_NAME NS_LITERAL_CSTRING("RejectForeignAllowList") +#define REJECTFOREIGNALLOWLIST_PREF "privacy.rejectForeign.allowList"_ns +#define REJECTFOREIGNALLOWLIST_NAME "RejectForeignAllowList"_ns namespace mozilla { diff --git a/toolkit/components/autocomplete/nsAutoCompleteController.cpp b/toolkit/components/autocomplete/nsAutoCompleteController.cpp index 6e9e52be72b6..c47677a95ba1 100644 --- a/toolkit/components/autocomplete/nsAutoCompleteController.cpp +++ b/toolkit/components/autocomplete/nsAutoCompleteController.cpp @@ -1662,7 +1662,7 @@ nsresult nsAutoCompleteController::CompleteValue(nsString& aValue) // Autocompleting something other than a URI from the middle. // Use the format "searchstring >> full string" to indicate to the user // what we are going to replace their search string with. - SetValueOfInputTo(mSearchString + NS_LITERAL_STRING(" >> ") + aValue, + SetValueOfInputTo(mSearchString + u" >> "_ns + aValue, nsIAutoCompleteInput::TEXTVALUE_REASON_COMPLETEDEFAULT); endSelect = mSearchString.Length() + 4 + aValue.Length(); diff --git a/toolkit/components/backgroundhangmonitor/BackgroundHangMonitor.cpp b/toolkit/components/backgroundhangmonitor/BackgroundHangMonitor.cpp index bde2638869f4..16c28de69830 100644 --- a/toolkit/components/backgroundhangmonitor/BackgroundHangMonitor.cpp +++ b/toolkit/components/backgroundhangmonitor/BackgroundHangMonitor.cpp @@ -142,7 +142,7 @@ BackgroundHangManager::Observe(nsISupports* aSubject, const char* aTopic, nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mPermahangFile)); if (NS_SUCCEEDED(rv)) { - mPermahangFile->AppendNative(NS_LITERAL_CSTRING("last_permahang.bin")); + mPermahangFile->AppendNative("last_permahang.bin"_ns); } else { mPermahangFile = nullptr; } diff --git a/toolkit/components/backgroundhangmonitor/HangAnnotations.cpp b/toolkit/components/backgroundhangmonitor/HangAnnotations.cpp index 5927232c0a1e..a8093c4781a0 100644 --- a/toolkit/components/backgroundhangmonitor/HangAnnotations.cpp +++ b/toolkit/components/backgroundhangmonitor/HangAnnotations.cpp @@ -43,9 +43,9 @@ void BackgroundHangAnnotations::AddAnnotation(const nsString& aName, void BackgroundHangAnnotations::AddAnnotation(const nsString& aName, const bool aData) { if (aData) { - AppendElement(HangAnnotation(aName, NS_LITERAL_STRING("true"))); + AppendElement(HangAnnotation(aName, u"true"_ns)); } else { - AppendElement(HangAnnotation(aName, NS_LITERAL_STRING("false"))); + AppendElement(HangAnnotation(aName, u"false"_ns)); } } diff --git a/toolkit/components/backgroundhangmonitor/HangDetails.cpp b/toolkit/components/backgroundhangmonitor/HangDetails.cpp index 0824a1ed0017..250bcfc216ab 100644 --- a/toolkit/components/backgroundhangmonitor/HangDetails.cpp +++ b/toolkit/components/backgroundhangmonitor/HangDetails.cpp @@ -585,8 +585,7 @@ Result ReadHangDetailsFromFile(nsIFile* aFile) { if (!annotations.SetCapacity(numAnnotations + 1, mozilla::fallible)) { return Err(NS_ERROR_FAILURE); } - annotations.AppendElement(HangAnnotation(NS_LITERAL_STRING("Unrecovered"), - NS_LITERAL_STRING("true"))); + annotations.AppendElement(HangAnnotation(u"Unrecovered"_ns, u"true"_ns)); for (size_t i = 0; i < numAnnotations; ++i) { HangAnnotation annot; diff --git a/toolkit/components/clearsitedata/ClearSiteData.cpp b/toolkit/components/clearsitedata/ClearSiteData.cpp index 34735894cbee..cf7d015465c2 100644 --- a/toolkit/components/clearsitedata/ClearSiteData.cpp +++ b/toolkit/components/clearsitedata/ClearSiteData.cpp @@ -222,8 +222,7 @@ uint32_t ClearSiteData::ParseHeader(nsIHttpChannel* aChannel, MOZ_ASSERT(aChannel); nsAutoCString headerValue; - nsresult rv = aChannel->GetResponseHeader( - NS_LITERAL_CSTRING("Clear-Site-Data"), headerValue); + nsresult rv = aChannel->GetResponseHeader("Clear-Site-Data"_ns, headerValue); if (NS_FAILED(rv)) { return 0; } @@ -296,8 +295,7 @@ void ClearSiteData::LogToConsoleInternal( return; } - httpChannel->AddConsoleReport(nsIScriptError::infoFlag, - NS_LITERAL_CSTRING("Clear-Site-Data"), + httpChannel->AddConsoleReport(nsIScriptError::infoFlag, "Clear-Site-Data"_ns, nsContentUtils::eSECURITY_PROPERTIES, uri, 0, 0, nsDependentCString(aMsg), aParams); } diff --git a/toolkit/components/extensions/ExtensionPolicyService.cpp b/toolkit/components/extensions/ExtensionPolicyService.cpp index b703342306a3..3c63e3f8f920 100644 --- a/toolkit/components/extensions/ExtensionPolicyService.cpp +++ b/toolkit/components/extensions/ExtensionPolicyService.cpp @@ -201,7 +201,7 @@ ExtensionPolicyService::CollectReports(nsIHandleReportCallback* aHandleReport, name.ReplaceSubstring("\\", ""); nsString url; - MOZ_TRY_VAR(url, ext->GetURL(NS_LITERAL_STRING(""))); + MOZ_TRY_VAR(url, ext->GetURL(u""_ns)); nsPrintfCString desc("Extension(id=%s, name=\"%s\", baseURL=%s)", id.get(), name.get(), NS_ConvertUTF16toUTF8(url).get()); @@ -210,10 +210,9 @@ ExtensionPolicyService::CollectReports(nsIHandleReportCallback* aHandleReport, nsCString path("extensions/"); path.Append(desc); - aHandleReport->Callback( - EmptyCString(), path, KIND_NONHEAP, UNITS_COUNT, 1, - NS_LITERAL_CSTRING("WebExtensions that are active in this session"), - aData); + aHandleReport->Callback(EmptyCString(), path, KIND_NONHEAP, UNITS_COUNT, 1, + "WebExtensions that are active in this session"_ns, + aData); } return NS_OK; @@ -267,7 +266,7 @@ nsresult ExtensionPolicyService::Observe(nsISupports* aSubject, mMessageManagers.PutEntry(mm); - mm->AddSystemEventListener(NS_LITERAL_STRING("unload"), this, false, false); + mm->AddSystemEventListener(u"unload"_ns, this, false, false); } else if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) { const nsCString converted = NS_ConvertUTF16toUTF8(aData); const char* pref = converted.get(); diff --git a/toolkit/components/extensions/webrequest/ChannelWrapper.cpp b/toolkit/components/extensions/webrequest/ChannelWrapper.cpp index 0fe90dd7b10f..df1e6a941069 100644 --- a/toolkit/components/extensions/webrequest/ChannelWrapper.cpp +++ b/toolkit/components/extensions/webrequest/ChannelWrapper.cpp @@ -46,8 +46,7 @@ using namespace JS; namespace mozilla { namespace extensions { -#define CHANNELWRAPPER_PROP_KEY \ - NS_LITERAL_STRING("ChannelWrapper::CachedInstance") +#define CHANNELWRAPPER_PROP_KEY u"ChannelWrapper::CachedInstance"_ns using CF = nsIClassifiedChannel::ClassificationFlags; using MUC = MozUrlClassificationFlags; @@ -535,7 +534,7 @@ const URLInfo& ChannelWrapper::FinalURLInfo() const { if (Type() == MozContentPolicyType::Websocket && (url.Scheme() == nsGkAtoms::http || url.Scheme() == nsGkAtoms::https)) { nsAutoCString spec(url.CSpec()); - spec.Replace(0, 4, NS_LITERAL_CSTRING("ws")); + spec.Replace(0, 4, "ws"_ns); Unused << NS_NewURI(getter_AddRefs(uri), spec); MOZ_RELEASE_ASSERT(uri); @@ -1021,7 +1020,7 @@ void ChannelWrapper::ErrorCheck() { mChannelEntry = nullptr; mFiredErrorEvent = true; ChannelWrapper_Binding::ClearCachedErrorStringValue(this); - FireEvent(NS_LITERAL_STRING("error")); + FireEvent(u"error"_ns); } } } @@ -1052,7 +1051,7 @@ ChannelWrapper::RequestListener::OnStartRequest(nsIRequest* request) { mChannelWrapper->mChannelEntry = nullptr; mChannelWrapper->mResponseStarted = true; mChannelWrapper->ErrorCheck(); - mChannelWrapper->FireEvent(NS_LITERAL_STRING("start")); + mChannelWrapper->FireEvent(u"start"_ns); return mOrigStreamListener->OnStartRequest(request); } @@ -1064,7 +1063,7 @@ ChannelWrapper::RequestListener::OnStopRequest(nsIRequest* request, mChannelWrapper->mChannelEntry = nullptr; mChannelWrapper->ErrorCheck(); - mChannelWrapper->FireEvent(NS_LITERAL_STRING("stop")); + mChannelWrapper->FireEvent(u"stop"_ns); return mOrigStreamListener->OnStopRequest(request, aStatus); } diff --git a/toolkit/components/extensions/webrequest/StreamFilter.cpp b/toolkit/components/extensions/webrequest/StreamFilter.cpp index cd6b44004c44..70d72f638e50 100644 --- a/toolkit/components/extensions/webrequest/StreamFilter.cpp +++ b/toolkit/components/extensions/webrequest/StreamFilter.cpp @@ -225,14 +225,14 @@ void StreamFilter::FireDataEvent(const nsTArray& aData) { auto buffer = ArrayBuffer::Create(cx, aData.Length(), aData.Elements()); if (!buffer) { // TODO: There is no way to recover from this. This chunk of data is lost. - FireErrorEvent(NS_LITERAL_STRING("Out of memory")); + FireErrorEvent(u"Out of memory"_ns); return; } init.mData.Init(buffer); RefPtr event = - StreamFilterDataEvent::Constructor(this, NS_LITERAL_STRING("data"), init); + StreamFilterDataEvent::Constructor(this, u"data"_ns, init); event->SetTrusted(true); DispatchEvent(*event); @@ -242,7 +242,7 @@ void StreamFilter::FireErrorEvent(const nsAString& aError) { MOZ_ASSERT(mError.IsEmpty()); mError = aError; - FireEvent(NS_LITERAL_STRING("error")); + FireEvent(u"error"_ns); } /***************************************************************************** diff --git a/toolkit/components/extensions/webrequest/StreamFilterChild.cpp b/toolkit/components/extensions/webrequest/StreamFilterChild.cpp index 99cc6e0bcf62..90a6e11ad2fe 100644 --- a/toolkit/components/extensions/webrequest/StreamFilterChild.cpp +++ b/toolkit/components/extensions/webrequest/StreamFilterChild.cpp @@ -216,7 +216,7 @@ void StreamFilterChild::SetNextState() { case State::FinishedTransferringData: if (mStreamFilter) { - mStreamFilter->FireEvent(NS_LITERAL_STRING("stop")); + mStreamFilter->FireEvent(u"stop"_ns); // We don't need access to the stream filter after this point, so break // our reference cycle, so that it can be collected if we're the last // reference. @@ -262,7 +262,7 @@ void StreamFilterChild::MaybeStopRequest() { default: mState = State::FinishedTransferringData; if (mStreamFilter) { - mStreamFilter->FireEvent(NS_LITERAL_STRING("stop")); + mStreamFilter->FireEvent(u"stop"_ns); // We don't need access to the stream filter after this point, so break // our reference cycle, so that it can be collected if we're the last // reference. @@ -284,7 +284,7 @@ void StreamFilterChild::RecvInitialized(bool aSuccess) { } else { mState = State::Error; if (mStreamFilter) { - mStreamFilter->FireErrorEvent(NS_LITERAL_STRING("Invalid request ID")); + mStreamFilter->FireErrorEvent(u"Invalid request ID"_ns); mStreamFilter = nullptr; } } @@ -425,7 +425,7 @@ IPCResult StreamFilterChild::RecvStartRequest() { mState = State::TransferringData; if (mStreamFilter) { - mStreamFilter->FireEvent(NS_LITERAL_STRING("start")); + mStreamFilter->FireEvent(u"start"_ns); Unused << mStreamFilter->CheckAlive(); } return IPC_OK(); diff --git a/toolkit/components/extensions/webrequest/StreamFilterParent.cpp b/toolkit/components/extensions/webrequest/StreamFilterParent.cpp index c2d7b316ce2d..6b41ea90e064 100644 --- a/toolkit/components/extensions/webrequest/StreamFilterParent.cpp +++ b/toolkit/components/extensions/webrequest/StreamFilterParent.cpp @@ -481,8 +481,7 @@ StreamFilterParent::OnStartRequest(nsIRequest* aRequest) { RunOnActorThread(FUNC, [=] { if (self->IPCActive()) { self->mState = State::Disconnected; - CheckResult( - self->SendError(NS_LITERAL_CSTRING("Channel redirected"))); + CheckResult(self->SendError("Channel redirected"_ns)); } }); } @@ -499,8 +498,8 @@ StreamFilterParent::OnStartRequest(nsIRequest* aRequest) { RunOnActorThread(FUNC, [=] { if (self->IPCActive()) { self->mState = State::Disconnected; - CheckResult(self->SendError( - NS_LITERAL_CSTRING("Channel is delivering cached alt-data"))); + CheckResult( + self->SendError("Channel is delivering cached alt-data"_ns)); } }); } diff --git a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp index 2ad7068590bd..f93abae14420 100644 --- a/toolkit/components/filewatcher/NativeFileWatcherWin.cpp +++ b/toolkit/components/filewatcher/NativeFileWatcherWin.cpp @@ -372,8 +372,7 @@ nsresult NativeFileWatcherIOTask::RunInternal() { WatchedResourceDescriptor* changedRes = mWatchedResourcesByHandle.Get((HANDLE)changedResourceHandle); - nsresult rv = - DispatchChangeCallbacks(changedRes, NS_LITERAL_STRING("*")); + nsresult rv = DispatchChangeCallbacks(changedRes, u"*"_ns); if (NS_FAILED(rv)) { // We failed to dispatch the error callbacks. Something very // bad happened to the main thread, so we bail out from the watcher diff --git a/toolkit/components/osfile/NativeOSFileInternals.cpp b/toolkit/components/osfile/NativeOSFileInternals.cpp index 89eda282908d..26b95730c4d6 100644 --- a/toolkit/components/osfile/NativeOSFileInternals.cpp +++ b/toolkit/components/osfile/NativeOSFileInternals.cpp @@ -663,14 +663,14 @@ class AbstractReadEvent : public AbstractDoEvent { /*Template file*/ nullptr); if (handle == INVALID_HANDLE_VALUE) { - Fail(NS_LITERAL_CSTRING("open"), nullptr, ::GetLastError()); + Fail("open"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } file = PR_ImportFile((PROsfd)handle); if (!file) { // |file| is closed by PR_ImportFile - Fail(NS_LITERAL_CSTRING("ImportFile"), nullptr, PR_GetOSError()); + Fail("ImportFile"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } @@ -679,7 +679,7 @@ class AbstractReadEvent : public AbstractDoEvent { NS_ConvertUTF16toUTF8 path(mPath); file = PR_OpenFile(path.get(), PR_RDONLY, 0); if (!file) { - Fail(NS_LITERAL_CSTRING("open"), nullptr, PR_GetOSError()); + Fail("open"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } @@ -687,18 +687,18 @@ class AbstractReadEvent : public AbstractDoEvent { PRFileInfo64 stat; if (PR_GetOpenFileInfo64(file, &stat) != PR_SUCCESS) { - Fail(NS_LITERAL_CSTRING("stat"), nullptr, PR_GetOSError()); + Fail("stat"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } uint64_t bytes = std::min((uint64_t)stat.size, mBytes); if (bytes > UINT32_MAX) { - Fail(NS_LITERAL_CSTRING("Arithmetics"), nullptr, OS_ERROR_INVAL); + Fail("Arithmetics"_ns, nullptr, OS_ERROR_INVAL); return NS_ERROR_FAILURE; } if (!aBuffer.Allocate(bytes)) { - Fail(NS_LITERAL_CSTRING("allocate"), nullptr, OS_ERROR_NOMEM); + Fail("allocate"_ns, nullptr, OS_ERROR_NOMEM); return NS_ERROR_FAILURE; } @@ -709,14 +709,14 @@ class AbstractReadEvent : public AbstractDoEvent { just_read = PR_Read(file, dest_chars + total_read, std::min(uint64_t(PR_INT32_MAX), bytes - total_read)); if (just_read == -1) { - Fail(NS_LITERAL_CSTRING("read"), nullptr, PR_GetOSError()); + Fail("read"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } total_read += just_read; } while (just_read != 0 && total_read < bytes); if (total_read != bytes) { // We seem to have a race condition here. - Fail(NS_LITERAL_CSTRING("read"), nullptr, OS_ERROR_RACE); + Fail("read"_ns, nullptr, OS_ERROR_RACE); return NS_ERROR_FAILURE; } @@ -810,13 +810,12 @@ class DoReadToStringEvent final : public AbstractReadEvent { MOZ_ASSERT(!NS_IsMainThread()); const Encoding* encoding = Encoding::ForLabel(mEncoding); if (!encoding) { - Fail(NS_LITERAL_CSTRING("Decode"), mResult.forget(), OS_ERROR_INVAL); + Fail("Decode"_ns, mResult.forget(), OS_ERROR_INVAL); return NS_ERROR_FAILURE; } mDecoder = encoding->NewDecoderWithBOMRemoval(); if (!mDecoder) { - Fail(NS_LITERAL_CSTRING("DecoderForEncoding"), mResult.forget(), - OS_ERROR_INVAL); + Fail("DecoderForEncoding"_ns, mResult.forget(), OS_ERROR_INVAL); return NS_ERROR_FAILURE; } @@ -832,16 +831,14 @@ class DoReadToStringEvent final : public AbstractReadEvent { CheckedInt needed = mDecoder->MaxUTF16BufferLength(src.Length()); if (!needed.isValid() || needed.value() > std::numeric_limits::max()) { - Fail(NS_LITERAL_CSTRING("arithmetics"), mResult.forget(), - OS_ERROR_TOO_LARGE); + Fail("arithmetics"_ns, mResult.forget(), OS_ERROR_TOO_LARGE); return; } nsString resultString; bool ok = resultString.SetLength(needed.value(), fallible); if (!ok) { - Fail(NS_LITERAL_CSTRING("allocation"), mResult.forget(), - OS_ERROR_TOO_LARGE); + Fail("allocation"_ns, mResult.forget(), OS_ERROR_TOO_LARGE); return; } @@ -860,8 +857,7 @@ class DoReadToStringEvent final : public AbstractReadEvent { Unused << hadErrors; ok = resultString.SetLength(written, fallible); if (!ok) { - Fail(NS_LITERAL_CSTRING("allocation"), mResult.forget(), - OS_ERROR_TOO_LARGE); + Fail("allocation"_ns, mResult.forget(), OS_ERROR_TOO_LARGE); return; } @@ -963,7 +959,7 @@ class DoWriteAtomicEvent : public AbstractDoEvent { // Check noOverwrite. if (mNoOverwrite && fileExists) { - Fail(NS_LITERAL_CSTRING("noOverwrite"), nullptr, OS_ERROR_FILE_EXISTS); + Fail("noOverwrite"_ns, nullptr, OS_ERROR_FILE_EXISTS); return NS_ERROR_FAILURE; } @@ -974,13 +970,13 @@ class DoWriteAtomicEvent : public AbstractDoEvent { // The file specified by mBackupTo exists, so we need to delete it // first. if (::DeleteFileW(mBackupTo.get()) == false) { - Fail(NS_LITERAL_CSTRING("delete"), nullptr, ::GetLastError()); + Fail("delete"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } } if (::MoveFileW(mPath.get(), mBackupTo.get()) == false) { - Fail(NS_LITERAL_CSTRING("rename"), nullptr, ::GetLastError()); + Fail("rename"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } #else @@ -988,13 +984,13 @@ class DoWriteAtomicEvent : public AbstractDoEvent { // The file specified by mBackupTo exists, so we need to delete it // first. if (PR_Delete(backupTo.get()) == PR_FAILURE) { - Fail(NS_LITERAL_CSTRING("delete"), nullptr, PR_GetOSError()); + Fail("delete"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } } if (PR_Rename(path.get(), backupTo.get()) == PR_FAILURE) { - Fail(NS_LITERAL_CSTRING("rename"), nullptr, PR_GetOSError()); + Fail("rename"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } #endif // defined(XP_WIN) @@ -1027,14 +1023,14 @@ class DoWriteAtomicEvent : public AbstractDoEvent { } if (handle == INVALID_HANDLE_VALUE) { - Fail(NS_LITERAL_CSTRING("open"), nullptr, ::GetLastError()); + Fail("open"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } file = PR_ImportFile((PROsfd)handle); if (!file) { // |file| is closed by PR_ImportFile - Fail(NS_LITERAL_CSTRING("ImportFile"), nullptr, PR_GetOSError()); + Fail("ImportFile"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } @@ -1050,7 +1046,7 @@ class DoWriteAtomicEvent : public AbstractDoEvent { } if (!file) { - Fail(NS_LITERAL_CSTRING("open"), nullptr, PR_GetOSError()); + Fail("open"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } #endif // defined(XP_WIN) @@ -1059,7 +1055,7 @@ class DoWriteAtomicEvent : public AbstractDoEvent { PR_Write(file, (void*)(mBuffer.get()), mBytes); if (bytesWrittenSuccess == -1) { - Fail(NS_LITERAL_CSTRING("write"), nullptr, PR_GetOSError()); + Fail("write"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } @@ -1070,12 +1066,12 @@ class DoWriteAtomicEvent : public AbstractDoEvent { // already renamed it as a part of backing it up. #if defined(XP_WIN) if (::DeleteFileW(mPath.get()) == false) { - Fail(NS_LITERAL_CSTRING("delete"), nullptr, ::GetLastError()); + Fail("delete"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } #else if (PR_Delete(path.get()) == PR_FAILURE) { - Fail(NS_LITERAL_CSTRING("delete"), nullptr, PR_GetOSError()); + Fail("delete"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } #endif // defined(XP_WIN) @@ -1083,12 +1079,12 @@ class DoWriteAtomicEvent : public AbstractDoEvent { #if defined(XP_WIN) if (::MoveFileW(mTmpPath.get(), mPath.get()) == false) { - Fail(NS_LITERAL_CSTRING("rename"), nullptr, ::GetLastError()); + Fail("rename"_ns, nullptr, ::GetLastError()); return NS_ERROR_FAILURE; } #else if (PR_Rename(tmpPath.get(), path.get()) == PR_FAILURE) { - Fail(NS_LITERAL_CSTRING("rename"), nullptr, PR_GetOSError()); + Fail("rename"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } #endif // defined(XP_WIN) @@ -1096,7 +1092,7 @@ class DoWriteAtomicEvent : public AbstractDoEvent { if (mFlush) { if (PR_Sync(file) == PR_FAILURE) { - Fail(NS_LITERAL_CSTRING("sync"), nullptr, PR_GetOSError()); + Fail("sync"_ns, nullptr, PR_GetOSError()); return NS_ERROR_FAILURE; } } diff --git a/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp b/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp index dfa26cc8512e..d0ead48d150a 100644 --- a/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp +++ b/toolkit/components/parentalcontrols/nsParentalControlsServiceWin.cpp @@ -85,7 +85,7 @@ nsParentalControlsService::nsParentalControlsService() } uint32_t filterOn = 0; - rv = regKey->ReadIntValue(NS_LITERAL_STRING("Filter On"), &filterOn); + rv = regKey->ReadIntValue(u"Filter On"_ns, &filterOn); if (NS_FAILED(rv)) { return; } diff --git a/toolkit/components/places/Database.cpp b/toolkit/components/places/Database.cpp index 0eab1d2c2d61..a670a3c483dd 100644 --- a/toolkit/components/places/Database.cpp +++ b/toolkit/components/places/Database.cpp @@ -41,9 +41,9 @@ #define RECENT_BACKUP_TIME_MICROSEC (int64_t)86400 * PR_USEC_PER_SEC // 24H // Filename of the database. -#define DATABASE_FILENAME NS_LITERAL_STRING("places.sqlite") +#define DATABASE_FILENAME u"places.sqlite"_ns // Filename of the icons database. -#define DATABASE_FAVICONS_FILENAME NS_LITERAL_STRING("favicons.sqlite") +#define DATABASE_FAVICONS_FILENAME u"favicons.sqlite"_ns // Set to the database file name when it was found corrupt by a previous // maintenance run. @@ -101,11 +101,9 @@ #define DATABASE_BUSY_TIMEOUT_MS 100 // This annotation is no longer used & is obsolete, but here for migration. -#define LAST_USED_ANNO \ - NS_LITERAL_CSTRING("bookmarkPropertiesDialog/folderLastUsed") +#define LAST_USED_ANNO "bookmarkPropertiesDialog/folderLastUsed"_ns // This is key in the meta table that the LAST_USED_ANNO is migrated to. -#define LAST_USED_FOLDERS_META_KEY \ - NS_LITERAL_CSTRING("places/bookmarks/edit/lastusedfolder") +#define LAST_USED_FOLDERS_META_KEY "places/bookmarks/edit/lastusedfolder"_ns // We use a fixed title for the mobile root to avoid marking the database as // corrupt if we can't look up the localized title in the string bundle. Sync @@ -129,13 +127,13 @@ namespace { * Get the filename for a corrupt database. */ nsString getCorruptFilename(const nsString& aDbFilename) { - return aDbFilename + NS_LITERAL_STRING(".corrupt"); + return aDbFilename + u".corrupt"_ns; } /** * Get the filename for a recover database. */ nsString getRecoverFilename(const nsString& aDbFilename) { - return aDbFilename + NS_LITERAL_STRING(".recover"); + return aDbFilename + u".recover"_ns; } /** @@ -230,7 +228,7 @@ nsresult CreateRoot(nsCOMPtr& aDBConn, // Create a new bookmark folder for the root. nsCOMPtr stmt; nsresult rv = aDBConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT INTO moz_bookmarks " "(type, position, title, dateAdded, lastModified, guid, parent, " "syncChangeCounter, syncStatus) " @@ -241,21 +239,20 @@ nsresult CreateRoot(nsCOMPtr& aDBConn, getter_AddRefs(stmt)); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("item_type"), + rv = stmt->BindInt32ByName("item_type"_ns, nsINavBookmarksService::TYPE_FOLDER); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("item_position"), position); + rv = stmt->BindInt32ByName("item_position"_ns, position); if (NS_FAILED(rv)) return rv; - rv = - stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_title"), titleString); + rv = stmt->BindUTF8StringByName("item_title"_ns, titleString); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("date_added"), timestamp); + rv = stmt->BindInt64ByName("date_added"_ns, timestamp); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("last_modified"), timestamp); + rv = stmt->BindInt64ByName("last_modified"_ns, timestamp); if (NS_FAILED(rv)) return rv; - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aGuid); + rv = stmt->BindUTF8StringByName("guid"_ns, aGuid); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("sync_status"), + rv = stmt->BindInt32ByName("sync_status"_ns, nsINavBookmarksService::SYNC_STATUS_NEW); if (NS_FAILED(rv)) return rv; rv = stmt->Execute(); @@ -273,8 +270,7 @@ nsresult SetupDurability(nsCOMPtr& aDBConn, // Volatile storage was requested. Use the in-memory journal (no // filesystem I/O) and don't sync the filesystem after writing. SetJournalMode(aDBConn, JOURNAL_MEMORY); - rv = aDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA synchronous = OFF")); + rv = aDBConn->ExecuteSimpleSQL("PRAGMA synchronous = OFF"_ns); NS_ENSURE_SUCCESS(rv, rv); } else { // Be sure to set journal mode after page_size. WAL would prevent the @@ -295,8 +291,7 @@ nsresult SetupDurability(nsCOMPtr& aDBConn, // Set synchronous to FULL to ensure maximum data integrity, even in // case of crashes or unclean shutdowns. - rv = aDBConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA synchronous = FULL")); + rv = aDBConn->ExecuteSimpleSQL("PRAGMA synchronous = FULL"_ns); NS_ENSURE_SUCCESS(rv, rv); } } @@ -322,11 +317,10 @@ nsresult SetupDurability(nsCOMPtr& aDBConn, nsresult AttachDatabase(nsCOMPtr& aDBConn, const nsACString& aPath, const nsACString& aName) { nsCOMPtr stmt; - nsresult rv = aDBConn->CreateStatement( - NS_LITERAL_CSTRING("ATTACH DATABASE :path AS ") + aName, - getter_AddRefs(stmt)); + nsresult rv = aDBConn->CreateStatement("ATTACH DATABASE :path AS "_ns + aName, + getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("path"), aPath); + rv = stmt->BindUTF8StringByName("path"_ns, aPath); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -479,7 +473,7 @@ nsresult Database::Init() { if (shutdownPhase) { DebugOnly rv = shutdownPhase->AddBlocker( static_cast(mClientsShutdown.get()), - NS_LITERAL_STRING(__FILE__), __LINE__, NS_LITERAL_STRING("")); + NS_LITERAL_STRING(__FILE__), __LINE__, u""_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -492,7 +486,7 @@ nsresult Database::Init() { if (shutdownPhase) { DebugOnly rv = shutdownPhase->AddBlocker( static_cast(mConnectionShutdown.get()), - NS_LITERAL_STRING(__FILE__), __LINE__, NS_LITERAL_STRING("")); + NS_LITERAL_STRING(__FILE__), __LINE__, u""_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); } } @@ -689,7 +683,7 @@ nsresult Database::EnsureFaviconsDatabaseAttached( bool fileExists = false; if (NS_SUCCEEDED(databaseFile->Exists(&fileExists)) && fileExists) { return AttachDatabase(mMainConn, NS_ConvertUTF16toUTF8(iconsPath), - NS_LITERAL_CSTRING("favicons")); + "favicons"_ns); } // Open the database file, this will also create it. @@ -709,15 +703,13 @@ nsresult Database::EnsureFaviconsDatabaseAttached( // Enable incremental vacuum for this database. Since it will contain even // large blobs and can be cleared with history, it's worth to have it. // Note that it will be necessary to manually use PRAGMA incremental_vacuum. - rv = conn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA auto_vacuum = INCREMENTAL")); + rv = conn->ExecuteSimpleSQL("PRAGMA auto_vacuum = INCREMENTAL"_ns); NS_ENSURE_SUCCESS(rv, rv); #if !defined(HAVE_64BIT_BUILD) // Ensure that temp tables are held in memory, not on disk, on 32 bit // platforms. - rv = conn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA temp_store = MEMORY")); + rv = conn->ExecuteSimpleSQL("PRAGMA temp_store = MEMORY"_ns); NS_ENSURE_SUCCESS(rv, rv); #endif @@ -747,7 +739,7 @@ nsresult Database::EnsureFaviconsDatabaseAttached( } rv = AttachDatabase(mMainConn, NS_ConvertUTF16toUTF8(iconsPath), - NS_LITERAL_CSTRING("favicons")); + "favicons"_ns); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -917,15 +909,14 @@ nsresult Database::TryToCloneTablesFromCorruptDatabase( rv = aStorage->OpenUnsharedDatabase(recoverFile, getter_AddRefs(conn)); NS_ENSURE_SUCCESS(rv, rv); - rv = AttachDatabase(conn, NS_ConvertUTF16toUTF8(path), - NS_LITERAL_CSTRING("corrupt")); + rv = AttachDatabase(conn, NS_ConvertUTF16toUTF8(path), "corrupt"_ns); NS_ENSURE_SUCCESS(rv, rv); mozStorageTransaction transaction(conn, false); // Copy the schema version. nsCOMPtr stmt; - (void)conn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA corrupt.user_version"), + (void)conn->CreateStatement("PRAGMA corrupt.user_version"_ns, getter_AddRefs(stmt)); NS_ENSURE_TRUE(stmt, NS_ERROR_OUT_OF_MEMORY); bool hasResult; @@ -937,7 +928,7 @@ nsresult Database::TryToCloneTablesFromCorruptDatabase( // Recreate the tables. rv = conn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT name, sql FROM corrupt.sqlite_master " "WHERE type = 'table' AND name BETWEEN 'moz_' AND 'moza'"), getter_AddRefs(stmt)); @@ -952,21 +943,19 @@ nsresult Database::TryToCloneTablesFromCorruptDatabase( rv = conn->ExecuteSimpleSQL(query); NS_ENSURE_SUCCESS(rv, rv); // Copy the table contents. - rv = conn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("INSERT INTO main.") + name + - NS_LITERAL_CSTRING(" SELECT * FROM corrupt.") + - name); + rv = conn->ExecuteSimpleSQL("INSERT INTO main."_ns + name + + " SELECT * FROM corrupt."_ns + name); if (NS_FAILED(rv)) { - rv = conn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("INSERT INTO main.") + name + - NS_LITERAL_CSTRING(" SELECT * FROM corrupt.") + name + - NS_LITERAL_CSTRING(" ORDER BY rowid DESC")); + rv = conn->ExecuteSimpleSQL("INSERT INTO main."_ns + name + + " SELECT * FROM corrupt."_ns + name + + " ORDER BY rowid DESC"_ns); } NS_ENSURE_SUCCESS(rv, rv); } // Recreate the indices. Doing this after data addition is faster. rv = conn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT sql FROM corrupt.sqlite_master " "WHERE type <> 'table' AND name BETWEEN 'moz_' AND 'moza'"), getter_AddRefs(stmt)); @@ -1015,7 +1004,7 @@ nsresult Database::SetupDatabaseConnection( // database file already existed with a different page size. nsCOMPtr statement; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING(MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA page_size"), + nsLiteralCString(MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA page_size"), getter_AddRefs(statement)); NS_ENSURE_SUCCESS(rv, rv); bool hasResult = false; @@ -1029,7 +1018,7 @@ nsresult Database::SetupDatabaseConnection( #if !defined(HAVE_64BIT_BUILD) // Ensure that temp tables are held in memory, not on disk, on 32 bit // platforms. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA temp_store = MEMORY")); NS_ENSURE_SUCCESS(rv, rv); #endif @@ -1042,7 +1031,7 @@ nsresult Database::SetupDatabaseConnection( (void)mMainConn->ExecuteSimpleSQL(busyTimeoutPragma); // Enable FOREIGN KEY support. This is a strict requirement. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( MOZ_STORAGE_UNIQUIFY_QUERY_STR "PRAGMA foreign_keys = ON")); NS_ENSURE_SUCCESS(rv, NS_ERROR_FILE_CORRUPTED); #ifdef DEBUG @@ -1052,8 +1041,7 @@ nsresult Database::SetupDatabaseConnection( // * if the SQLite library in use doesn't support them // Since we need foreign_keys, let's at least assert in debug mode. nsCOMPtr stmt; - mMainConn->CreateStatement(NS_LITERAL_CSTRING("PRAGMA foreign_keys"), - getter_AddRefs(stmt)); + mMainConn->CreateStatement("PRAGMA foreign_keys"_ns, getter_AddRefs(stmt)); bool hasResult = false; if (stmt && NS_SUCCEEDED(stmt->ExecuteStep(&hasResult)) && hasResult) { int32_t fkState = stmt->AsInt32(0); @@ -1112,8 +1100,7 @@ nsresult Database::InitSchema(bool* aDatabaseMigrated) { // regardless of its success. if (mShouldVacuumIcons) { mShouldVacuumIcons = false; - MOZ_ALWAYS_SUCCEEDS( - mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM favicons"))); + MOZ_ALWAYS_SUCCEEDS(mMainConn->ExecuteSimpleSQL("VACUUM favicons"_ns)); } if (mShouldConvertIconPayloads) { mShouldConvertIconPayloads = false; @@ -1373,12 +1360,12 @@ nsresult Database::CheckRoots() { nsCOMPtr stmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT guid, id, position, parent FROM moz_bookmarks " - "WHERE guid IN ( " - "'" ROOT_GUID "', '" MENU_ROOT_GUID - "', '" TOOLBAR_ROOT_GUID "', " - "'" TAGS_ROOT_GUID "', '" UNFILED_ROOT_GUID - "', '" MOBILE_ROOT_GUID "' )"), + nsLiteralCString("SELECT guid, id, position, parent FROM moz_bookmarks " + "WHERE guid IN ( " + "'" ROOT_GUID "', '" MENU_ROOT_GUID + "', '" TOOLBAR_ROOT_GUID "', " + "'" TAGS_ROOT_GUID "', '" UNFILED_ROOT_GUID + "', '" MOBILE_ROOT_GUID "' )"), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); @@ -1427,9 +1414,8 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, if (mRootId < 1) { // The first root's title is an empty string. - rv = CreateRoot(mMainConn, NS_LITERAL_CSTRING("places"), - NS_LITERAL_CSTRING("root________"), EmptyCString(), 0, - mRootId); + rv = CreateRoot(mMainConn, "places"_ns, "root________"_ns, EmptyCString(), + 0, mRootId); if (NS_FAILED(rv)) return rv; } @@ -1439,34 +1425,30 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, // For the other roots, the UI doesn't rely on the value in the database, so // just set it to something simple to make it easier for humans to read. if (mMenuRootId < 1) { - rv = CreateRoot(mMainConn, NS_LITERAL_CSTRING("menu"), - NS_LITERAL_CSTRING("menu________"), - NS_LITERAL_CSTRING("menu"), position, mMenuRootId); + rv = CreateRoot(mMainConn, "menu"_ns, "menu________"_ns, "menu"_ns, + position, mMenuRootId); if (NS_FAILED(rv)) return rv; position++; } if (mToolbarRootId < 1) { - rv = CreateRoot(mMainConn, NS_LITERAL_CSTRING("toolbar"), - NS_LITERAL_CSTRING("toolbar_____"), - NS_LITERAL_CSTRING("toolbar"), position, mToolbarRootId); + rv = CreateRoot(mMainConn, "toolbar"_ns, "toolbar_____"_ns, "toolbar"_ns, + position, mToolbarRootId); if (NS_FAILED(rv)) return rv; position++; } if (mTagsRootId < 1) { - rv = CreateRoot(mMainConn, NS_LITERAL_CSTRING("tags"), - NS_LITERAL_CSTRING("tags________"), - NS_LITERAL_CSTRING("tags"), position, mTagsRootId); + rv = CreateRoot(mMainConn, "tags"_ns, "tags________"_ns, "tags"_ns, + position, mTagsRootId); if (NS_FAILED(rv)) return rv; position++; } if (mUnfiledRootId < 1) { if (NS_FAILED(rv)) return rv; - rv = CreateRoot(mMainConn, NS_LITERAL_CSTRING("unfiled"), - NS_LITERAL_CSTRING("unfiled_____"), - NS_LITERAL_CSTRING("unfiled"), position, mUnfiledRootId); + rv = CreateRoot(mMainConn, "unfiled"_ns, "unfiled_____"_ns, "unfiled"_ns, + position, mUnfiledRootId); if (NS_FAILED(rv)) return rv; position++; } @@ -1477,17 +1459,15 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, { nsCOMPtr mobileRootSyncStatusStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("UPDATE moz_bookmarks SET syncStatus = " - ":sync_status WHERE id = :id"), + nsLiteralCString("UPDATE moz_bookmarks SET syncStatus = " + ":sync_status WHERE id = :id"), getter_AddRefs(mobileRootSyncStatusStmt)); if (NS_FAILED(rv)) return rv; rv = mobileRootSyncStatusStmt->BindInt32ByName( - NS_LITERAL_CSTRING("sync_status"), - nsINavBookmarksService::SYNC_STATUS_NEW); + "sync_status"_ns, nsINavBookmarksService::SYNC_STATUS_NEW); if (NS_FAILED(rv)) return rv; - rv = mobileRootSyncStatusStmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), - mobileRootId); + rv = mobileRootSyncStatusStmt->BindInt64ByName("id"_ns, mobileRootId); if (NS_FAILED(rv)) return rv; rv = mobileRootSyncStatusStmt->Execute(); @@ -1504,7 +1484,7 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, // At least one root had the wrong parent, so we need to ensure that // all roots are parented correctly, fix their positions, and bump the // Sync change counter. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TEMP TRIGGER moz_ensure_bookmark_roots_trigger " "AFTER UPDATE OF parent ON moz_bookmarks FOR EACH ROW " "WHEN OLD.parent <> NEW.parent " @@ -1528,12 +1508,12 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, if (NS_FAILED(rv)) return rv; auto guard = MakeScopeExit([&]() { Unused << mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER moz_ensure_bookmark_roots_trigger")); + "DROP TRIGGER moz_ensure_bookmark_roots_trigger"_ns); }); nsCOMPtr reparentStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "UPDATE moz_bookmarks SET " "parent = CASE id WHEN :root_id THEN 0 ELSE :root_id END " "WHERE id IN (:root_id, :menu_root_id, :toolbar_root_id, " @@ -1542,22 +1522,17 @@ nsresult Database::EnsureBookmarkRoots(const int32_t startPosition, getter_AddRefs(reparentStmt)); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("root_id"), mRootId); + rv = reparentStmt->BindInt64ByName("root_id"_ns, mRootId); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("menu_root_id"), - mMenuRootId); + rv = reparentStmt->BindInt64ByName("menu_root_id"_ns, mMenuRootId); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("toolbar_root_id"), - mToolbarRootId); + rv = reparentStmt->BindInt64ByName("toolbar_root_id"_ns, mToolbarRootId); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("tags_root_id"), - mTagsRootId); + rv = reparentStmt->BindInt64ByName("tags_root_id"_ns, mTagsRootId); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("unfiled_root_id"), - mUnfiledRootId); + rv = reparentStmt->BindInt64ByName("unfiled_root_id"_ns, mUnfiledRootId); if (NS_FAILED(rv)) return rv; - rv = reparentStmt->BindInt64ByName(NS_LITERAL_CSTRING("mobile_root_id"), - mMobileRootId); + rv = reparentStmt->BindInt64ByName("mobile_root_id"_ns, mMobileRootId); if (NS_FAILED(rv)) return rv; rv = reparentStmt->Execute(); @@ -1669,37 +1644,36 @@ nsresult Database::InitTempEntities() { nsresult Database::MigrateV36Up() { // Add sync status and change counter tracking columns for bookmarks. nsCOMPtr syncStatusStmt; - nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT syncStatus FROM moz_bookmarks"), - getter_AddRefs(syncStatusStmt)); + nsresult rv = + mMainConn->CreateStatement("SELECT syncStatus FROM moz_bookmarks"_ns, + getter_AddRefs(syncStatusStmt)); if (NS_FAILED(rv)) { // We default to SYNC_STATUS_UNKNOWN = 0 for existing bookmarks, matching // the bookmark restore behavior. If Sync is set up, we'll update the status // to SYNC_STATUS_NORMAL = 2 before the first post-migration sync. rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("ALTER TABLE moz_bookmarks " - "ADD COLUMN syncStatus INTEGER DEFAULT 0 NOT NULL")); + nsLiteralCString("ALTER TABLE moz_bookmarks " + "ADD COLUMN syncStatus INTEGER DEFAULT 0 NOT NULL")); NS_ENSURE_SUCCESS(rv, rv); } nsCOMPtr syncChangeCounterStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT syncChangeCounter FROM moz_bookmarks"), + "SELECT syncChangeCounter FROM moz_bookmarks"_ns, getter_AddRefs(syncChangeCounterStmt)); if (NS_FAILED(rv)) { // The change counter starts at 1 for all local bookmarks. It's incremented // for each modification that should trigger a sync, and decremented after // the modified bookmark is uploaded to the server. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_bookmarks " "ADD COLUMN syncChangeCounter INTEGER DEFAULT 1 NOT NULL")); NS_ENSURE_SUCCESS(rv, rv); } nsCOMPtr tombstoneTableStmt; - rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT 1 FROM moz_bookmarks_deleted"), - getter_AddRefs(tombstoneTableStmt)); + rv = mMainConn->CreateStatement("SELECT 1 FROM moz_bookmarks_deleted"_ns, + getter_AddRefs(tombstoneTableStmt)); if (NS_FAILED(rv)) { rv = mMainConn->ExecuteSimpleSQL(CREATE_MOZ_BOOKMARKS_DELETED); NS_ENSURE_SUCCESS(rv, rv); @@ -1716,8 +1690,8 @@ nsresult Database::MigrateV37Up() { // First, check if the old favicons table still exists. nsCOMPtr stmt; - nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT url FROM moz_favicons"), getter_AddRefs(stmt)); + nsresult rv = mMainConn->CreateStatement("SELECT url FROM moz_favicons"_ns, + getter_AddRefs(stmt)); if (NS_FAILED(rv)) { // The table has already been removed, nothing to do. return NS_OK; @@ -1728,7 +1702,7 @@ nsresult Database::MigrateV37Up() { // try to convert the unsupported payloads, or remove them. // Add pages. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO moz_pages_w_icons (page_url, page_url_hash) " "SELECT h.url, hash(h.url) " "FROM moz_places h " @@ -1738,7 +1712,7 @@ nsresult Database::MigrateV37Up() { // first load. // Note: we use a peculiarity of Sqlite here, where the column affinity // is not enforced, thanks to that we can store a string in an integer column. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT INTO moz_icons (icon_url, fixed_icon_url_hash, width, data) " "SELECT url, hash(fixup_url(url)), " "(CASE WHEN mime_type = 'image/png' THEN 16 " @@ -1748,7 +1722,7 @@ nsresult Database::MigrateV37Up() { "WHERE LENGTH(data) > 0 ")); NS_ENSURE_SUCCESS(rv, rv); // Create relations. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO moz_icons_to_pages (page_id, icon_id) " "SELECT (SELECT id FROM moz_pages_w_icons " "WHERE page_url_hash = h.url_hash " @@ -1760,12 +1734,11 @@ nsresult Database::MigrateV37Up() { "JOIN moz_places h on f.id = h.favicon_id")); NS_ENSURE_SUCCESS(rv, rv); // Remove old favicons and relations. - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_favicons")); + rv = mMainConn->ExecuteSimpleSQL("DELETE FROM moz_favicons"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_places SET favicon_id = NULL")); + rv = + mMainConn->ExecuteSimpleSQL("UPDATE moz_places SET favicon_id = NULL"_ns); NS_ENSURE_SUCCESS(rv, rv); // The async favicons conversion will happen at the end of the normal schema @@ -1778,15 +1751,14 @@ nsresult Database::MigrateV37Up() { nsresult Database::MigrateV38Up() { nsCOMPtr stmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( - "SELECT description, preview_image_url FROM moz_places"), + "SELECT description, preview_image_url FROM moz_places"_ns, getter_AddRefs(stmt)); if (NS_FAILED(rv)) { - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "ALTER TABLE moz_places ADD COLUMN description TEXT")); + rv = mMainConn->ExecuteSimpleSQL( + "ALTER TABLE moz_places ADD COLUMN description TEXT"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_places ADD COLUMN preview_image_url TEXT")); NS_ENSURE_SUCCESS(rv, rv); } @@ -1808,19 +1780,19 @@ nsresult Database::MigrateV40Up() { // Due to this, on downgrade some of these may not match, it should be limited // to unicode and very long urls though. nsresult rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_places " - "SET url_hash = hash(url) " - "WHERE url_hash <> hash(url)")); + nsLiteralCString("UPDATE moz_places " + "SET url_hash = hash(url) " + "WHERE url_hash <> hash(url)")); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_icons " "SET fixed_icon_url_hash = hash(fixup_url(icon_url)) " "WHERE fixed_icon_url_hash <> hash(fixup_url(icon_url))")); NS_ENSURE_SUCCESS(rv, rv); rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_pages_w_icons " - "SET page_url_hash = hash(page_url) " - "WHERE page_url_hash <> hash(page_url)")); + nsLiteralCString("UPDATE moz_pages_w_icons " + "SET page_url_hash = hash(page_url) " + "WHERE page_url_hash <> hash(page_url)")); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -1828,10 +1800,9 @@ nsresult Database::MigrateV40Up() { nsresult Database::MigrateV41Up() { // Remove old favicons entities. nsresult rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP INDEX IF EXISTS moz_places_faviconindex")); + "DROP INDEX IF EXISTS moz_places_faviconindex"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TABLE IF EXISTS moz_favicons")); + rv = mMainConn->ExecuteSimpleSQL("DROP TABLE IF EXISTS moz_favicons"_ns); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -1842,9 +1813,8 @@ nsresult Database::MigrateV42Up() { int32_t vacuum = 0; { nsCOMPtr stmt; - nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("PRAGMA favicons.auto_vacuum"), - getter_AddRefs(stmt)); + nsresult rv = mMainConn->CreateStatement("PRAGMA favicons.auto_vacuum"_ns, + getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); bool hasResult = false; if (NS_SUCCEEDED(stmt->ExecuteStep(&hasResult)) && hasResult) { @@ -1853,7 +1823,7 @@ nsresult Database::MigrateV42Up() { } if (vacuum != 2) { nsresult rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("PRAGMA favicons.auto_vacuum = INCREMENTAL")); + "PRAGMA favicons.auto_vacuum = INCREMENTAL"_ns); NS_ENSURE_SUCCESS(rv, rv); // For the change to be effective, we must vacuum the database. mShouldVacuumIcons = true; @@ -1869,27 +1839,27 @@ nsresult Database::MigrateV43Up() { // This may cause a dataloss, but the only alternative would be to modify the // related url, and that's far more complex. nsresult rv = - mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING("DELETE FROM moz_keywords " - "WHERE post_data ISNULL " - "AND id NOT IN ( " - "SELECT MAX(id) " - "FROM moz_keywords " - "WHERE post_data ISNULL " - "GROUP BY place_id " - ")")); + mMainConn->ExecuteSimpleSQL(nsLiteralCString("DELETE FROM moz_keywords " + "WHERE post_data ISNULL " + "AND id NOT IN ( " + "SELECT MAX(id) " + "FROM moz_keywords " + "WHERE post_data ISNULL " + "GROUP BY place_id " + ")")); NS_ENSURE_SUCCESS(rv, rv); // We must recalculate foreign_count for all the touched places. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_places " "SET foreign_count = (SELECT count(*) FROM moz_bookmarks WHERE fk = " "moz_places.id) + " "(SELECT count(*) FROM moz_keywords WHERE place_id = moz_places.id) " "WHERE id IN (SELECT DISTINCT place_id FROM moz_keywords) ")); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_keywords " - "SET post_data = '' " - "WHERE post_data ISNULL ")); + rv = + mMainConn->ExecuteSimpleSQL(nsLiteralCString("UPDATE moz_keywords " + "SET post_data = '' " + "WHERE post_data ISNULL ")); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1900,7 +1870,7 @@ nsresult Database::MigrateV44Up() { // Install a temp trigger to clean up linked tables when the main // bookmarks are deleted. - nsresult rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TEMP TRIGGER moz_migrate_bookmarks_trigger " "AFTER DELETE ON moz_bookmarks FOR EACH ROW " "BEGIN " @@ -1919,7 +1889,7 @@ nsresult Database::MigrateV44Up() { // This trigger listens for moz_places deletes, and updates moz_annos and // moz_keywords accordingly. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "CREATE TEMP TRIGGER moz_migrate_annos_trigger " "AFTER UPDATE ON moz_places FOR EACH ROW " // Only remove from moz_places if we don't have any remaining keywords @@ -1943,35 +1913,35 @@ nsresult Database::MigrateV44Up() { // Listens to moz_keyword deletions, to ensure moz_places gets the // foreign_count updated corrrectly. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "CREATE TEMP TRIGGER moz_migrate_keyword_trigger " - "AFTER DELETE ON moz_keywords FOR EACH ROW " - "BEGIN " - // If we remove a keyword, then reduce the foreign_count. - "UPDATE moz_places " - "SET foreign_count = foreign_count - 1 " - "WHERE id = OLD.place_id; " - "END ")); + rv = mMainConn->ExecuteSimpleSQL( + nsLiteralCString("CREATE TEMP TRIGGER moz_migrate_keyword_trigger " + "AFTER DELETE ON moz_keywords FOR EACH ROW " + "BEGIN " + // If we remove a keyword, then reduce the foreign_count. + "UPDATE moz_places " + "SET foreign_count = foreign_count - 1 " + "WHERE id = OLD.place_id; " + "END ")); if (NS_FAILED(rv)) return rv; // First of all, find the non-builtin roots. nsCOMPtr deleteStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("WITH RECURSIVE " - "itemsToRemove(id, guid) AS ( " - "SELECT b.id, b.guid FROM moz_bookmarks b " - "JOIN moz_bookmarks p ON b.parent = p.id " - "WHERE p.guid = 'root________' AND " - "b.guid NOT IN ('menu________', 'toolbar_____', " - "'tags________', 'unfiled_____', 'mobile______') " - "UNION ALL " - "SELECT b.id, b.guid FROM moz_bookmarks b " - "JOIN itemsToRemove d ON d.id = b.parent " - "WHERE b.guid NOT IN ('menu________', 'toolbar_____', " - "'tags________', 'unfiled_____', 'mobile______') " - ") " - "DELETE FROM moz_bookmarks " - "WHERE id IN (SELECT id FROM itemsToRemove) "), + nsLiteralCString("WITH RECURSIVE " + "itemsToRemove(id, guid) AS ( " + "SELECT b.id, b.guid FROM moz_bookmarks b " + "JOIN moz_bookmarks p ON b.parent = p.id " + "WHERE p.guid = 'root________' AND " + "b.guid NOT IN ('menu________', 'toolbar_____', " + "'tags________', 'unfiled_____', 'mobile______') " + "UNION ALL " + "SELECT b.id, b.guid FROM moz_bookmarks b " + "JOIN itemsToRemove d ON d.id = b.parent " + "WHERE b.guid NOT IN ('menu________', 'toolbar_____', " + "'tags________', 'unfiled_____', 'mobile______') " + ") " + "DELETE FROM moz_bookmarks " + "WHERE id IN (SELECT id FROM itemsToRemove) "), getter_AddRefs(deleteStmt)); if (NS_FAILED(rv)) return rv; @@ -1983,33 +1953,33 @@ nsresult Database::MigrateV44Up() { // so that we can make use of the keyword trigger to update the counts in // moz_places. rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_keywords WHERE place_id IN ( " - "SELECT h.id FROM moz_keywords k " - "JOIN moz_places h ON h.id = k.place_id " - "GROUP BY place_id HAVING h.foreign_count = count(*) " - ")")); + nsLiteralCString("DELETE FROM moz_keywords WHERE place_id IN ( " + "SELECT h.id FROM moz_keywords k " + "JOIN moz_places h ON h.id = k.place_id " + "GROUP BY place_id HAVING h.foreign_count = count(*) " + ")")); if (NS_FAILED(rv)) return rv; // Now remove the temp triggers. rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER moz_migrate_bookmarks_trigger ")); + "DROP TRIGGER moz_migrate_bookmarks_trigger "_ns); if (NS_FAILED(rv)) return rv; - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER moz_migrate_annos_trigger ")); + rv = + mMainConn->ExecuteSimpleSQL("DROP TRIGGER moz_migrate_annos_trigger "_ns); if (NS_FAILED(rv)) return rv; rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DROP TRIGGER moz_migrate_keyword_trigger ")); + "DROP TRIGGER moz_migrate_keyword_trigger "_ns); if (NS_FAILED(rv)) return rv; // Cleanup any orphan annotation attributes. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "DELETE FROM moz_anno_attributes WHERE id IN ( " - "SELECT id FROM moz_anno_attributes n " - "EXCEPT " - "SELECT DISTINCT anno_attribute_id FROM moz_annos " - "EXCEPT " - "SELECT DISTINCT anno_attribute_id FROM moz_items_annos " - ")")); + rv = mMainConn->ExecuteSimpleSQL( + nsLiteralCString("DELETE FROM moz_anno_attributes WHERE id IN ( " + "SELECT id FROM moz_anno_attributes n " + "EXCEPT " + "SELECT DISTINCT anno_attribute_id FROM moz_annos " + "EXCEPT " + "SELECT DISTINCT anno_attribute_id FROM moz_items_annos " + ")")); if (NS_FAILED(rv)) return rv; return NS_OK; @@ -2017,9 +1987,8 @@ nsresult Database::MigrateV44Up() { nsresult Database::MigrateV45Up() { nsCOMPtr metaTableStmt; - nsresult rv = - mMainConn->CreateStatement(NS_LITERAL_CSTRING("SELECT 1 FROM moz_meta"), - getter_AddRefs(metaTableStmt)); + nsresult rv = mMainConn->CreateStatement("SELECT 1 FROM moz_meta"_ns, + getter_AddRefs(metaTableStmt)); if (NS_FAILED(rv)) { rv = mMainConn->ExecuteSimpleSQL(CREATE_MOZ_META); NS_ENSURE_SUCCESS(rv, rv); @@ -2030,7 +1999,7 @@ nsresult Database::MigrateV45Up() { nsresult Database::MigrateV46Up() { // Convert the existing queries. For simplicity we assume the user didn't // edit these queries, and just do a 1:1 conversion. - nsresult rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_places " "SET url = IFNULL('place:tag=' || ( " "SELECT title FROM moz_bookmarks " @@ -2043,15 +2012,15 @@ nsresult Database::MigrateV46Up() { "WHERE id = CAST(get_query_param(substr(url, 7), 'folder') AS INT)) ")); // Recalculate hashes for all tag queries. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( - "UPDATE moz_places SET url_hash = hash(url) " - "WHERE url_hash BETWEEN hash('place', 'prefix_lo') AND " - "hash('place', 'prefix_hi') " - "AND url LIKE '%tag=%' ")); + rv = mMainConn->ExecuteSimpleSQL( + nsLiteralCString("UPDATE moz_places SET url_hash = hash(url) " + "WHERE url_hash BETWEEN hash('place', 'prefix_lo') AND " + "hash('place', 'prefix_hi') " + "AND url LIKE '%tag=%' ")); NS_ENSURE_SUCCESS(rv, rv); // Update Sync fields for all tag queries. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_bookmarks SET syncChangeCounter = syncChangeCounter + 1 " "WHERE fk IN ( " "SELECT id FROM moz_places " @@ -2068,13 +2037,13 @@ nsresult Database::MigrateV47Up() { // Since the original url was an invalid query, we replace NULLs with an // empty query. nsresult rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_places " - "SET url = 'place:excludeItems=1', url_hash = " - "hash('place:excludeItems=1') " - "WHERE url ISNULL ")); + nsLiteralCString("UPDATE moz_places " + "SET url = 'place:excludeItems=1', url_hash = " + "hash('place:excludeItems=1') " + "WHERE url ISNULL ")); NS_ENSURE_SUCCESS(rv, rv); // Update Sync fields for these queries. - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_bookmarks SET syncChangeCounter = syncChangeCounter + 1 " "WHERE fk IN ( " "SELECT id FROM moz_places " @@ -2088,31 +2057,30 @@ nsresult Database::MigrateV47Up() { nsresult Database::MigrateV48Up() { // Create and populate moz_origins. nsCOMPtr stmt; - nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT * FROM moz_origins; "), getter_AddRefs(stmt)); + nsresult rv = mMainConn->CreateStatement("SELECT * FROM moz_origins; "_ns, + getter_AddRefs(stmt)); if (NS_FAILED(rv)) { rv = mMainConn->ExecuteSimpleSQL(CREATE_MOZ_ORIGINS); NS_ENSURE_SUCCESS(rv, rv); } - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR IGNORE INTO moz_origins (prefix, host, frecency) " "SELECT get_prefix(url), get_host_and_port(url), -1 " "FROM moz_places; ")); NS_ENSURE_SUCCESS(rv, rv); // Add and populate moz_places.origin_id. - rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT origin_id FROM moz_places; "), - getter_AddRefs(stmt)); + rv = mMainConn->CreateStatement("SELECT origin_id FROM moz_places; "_ns, + getter_AddRefs(stmt)); if (NS_FAILED(rv)) { - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "ALTER TABLE moz_places " "ADD COLUMN origin_id INTEGER REFERENCES moz_origins(id); ")); NS_ENSURE_SUCCESS(rv, rv); } rv = mMainConn->ExecuteSimpleSQL(CREATE_IDX_MOZ_PLACES_ORIGIN_ID); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_places " "SET origin_id = ( " "SELECT id FROM moz_origins " @@ -2123,8 +2091,7 @@ nsresult Database::MigrateV48Up() { // From this point on, nobody should use moz_hosts again. Empty it so that we // don't leak the user's history, but don't remove it yet so that the user can // downgrade. - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_hosts; ")); + rv = mMainConn->ExecuteSimpleSQL("DELETE FROM moz_hosts; "_ns); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -2145,11 +2112,10 @@ nsresult Database::MigrateV50Up() { // simplest thing to do is to pull the urls out, and process them manually. nsCOMPtr stmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( - "SELECT id, url FROM moz_places " - "WHERE url_hash BETWEEN hash('place', 'prefix_lo') AND " - "hash('place', 'prefix_hi') " - "AND url LIKE '%folder=%' "), + nsLiteralCString("SELECT id, url FROM moz_places " + "WHERE url_hash BETWEEN hash('place', 'prefix_lo') AND " + "hash('place', 'prefix_hi') " + "AND url LIKE '%folder=%' "), getter_AddRefs(stmt)); if (NS_FAILED(rv)) return rv; @@ -2186,15 +2152,15 @@ nsresult Database::MigrateV50Up() { nsCOMPtr updateStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("UPDATE moz_places " - "SET url = :url, url_hash = hash(:url) " - "WHERE id = :placeId "), + nsLiteralCString("UPDATE moz_places " + "SET url = :url, url_hash = hash(:url) " + "WHERE id = :placeId "), getter_AddRefs(updateStmt)); if (NS_FAILED(rv)) return rv; - rv = URIBinder::Bind(updateStmt, NS_LITERAL_CSTRING("url"), url); + rv = URIBinder::Bind(updateStmt, "url"_ns, url); if (NS_FAILED(rv)) return rv; - rv = updateStmt->BindInt64ByName(NS_LITERAL_CSTRING("placeId"), placeId); + rv = updateStmt->BindInt64ByName("placeId"_ns, placeId); if (NS_FAILED(rv)) return rv; rv = updateStmt->Execute(); @@ -2203,13 +2169,13 @@ nsresult Database::MigrateV50Up() { // Update Sync fields for these queries. nsCOMPtr syncStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("UPDATE moz_bookmarks SET syncChangeCounter = " - "syncChangeCounter + 1 " - "WHERE fk = :placeId "), + nsLiteralCString("UPDATE moz_bookmarks SET syncChangeCounter = " + "syncChangeCounter + 1 " + "WHERE fk = :placeId "), getter_AddRefs(syncStmt)); if (NS_FAILED(rv)) return rv; - rv = syncStmt->BindInt64ByName(NS_LITERAL_CSTRING("placeId"), placeId); + rv = syncStmt->BindInt64ByName("placeId"_ns, placeId); if (NS_FAILED(rv)) return rv; rv = syncStmt->Execute(); @@ -2231,10 +2197,10 @@ struct StringWriteFunc : public JSONWriteFunc { nsresult Database::MigrateV51Up() { nsCOMPtr stmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT b.guid FROM moz_anno_attributes n " - "JOIN moz_items_annos a ON n.id = a.anno_attribute_id " - "JOIN moz_bookmarks b ON a.item_id = b.id " - "WHERE n.name = :anno_name ORDER BY a.content DESC"), + nsLiteralCString("SELECT b.guid FROM moz_anno_attributes n " + "JOIN moz_items_annos a ON n.id = a.anno_attribute_id " + "JOIN moz_bookmarks b ON a.item_id = b.id " + "WHERE n.name = :anno_name ORDER BY a.content DESC"), getter_AddRefs(stmt)); if (NS_FAILED(rv)) { MOZ_ASSERT(false, @@ -2242,8 +2208,7 @@ nsresult Database::MigrateV51Up() { return NS_OK; }; - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), - LAST_USED_ANNO); + rv = stmt->BindUTF8StringByName("anno_name"_ns, LAST_USED_ANNO); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString json; @@ -2265,39 +2230,36 @@ nsresult Database::MigrateV51Up() { } rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("INSERT OR REPLACE INTO moz_meta " - "VALUES (:key, :value) "), + nsLiteralCString("INSERT OR REPLACE INTO moz_meta " + "VALUES (:key, :value) "), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("key"), - LAST_USED_FOLDERS_META_KEY); + rv = stmt->BindUTF8StringByName("key"_ns, LAST_USED_FOLDERS_META_KEY); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("value"), json); + rv = stmt->BindUTF8StringByName("value"_ns, json); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); // Clean up the now redundant annotations. rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "DELETE FROM moz_items_annos WHERE anno_attribute_id = " "(SELECT id FROM moz_anno_attributes WHERE name = :anno_name) "), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), - LAST_USED_ANNO); + rv = stmt->BindUTF8StringByName("anno_name"_ns, LAST_USED_ANNO); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "DELETE FROM moz_anno_attributes WHERE name = :anno_name "), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), - LAST_USED_ANNO); + rv = stmt->BindUTF8StringByName("anno_name"_ns, LAST_USED_ANNO); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -2338,7 +2300,7 @@ MigrateV52OriginFrecenciesRunnable::Run() { } // We do the work in chunks, or the wal journal may grow too much. - nsresult rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = mDBConn->ExecuteSimpleSQL(nsLiteralCString( "UPDATE moz_origins " "SET frecency = ( " "SELECT CAST(TOTAL(frecency) AS INTEGER) " @@ -2354,10 +2316,10 @@ MigrateV52OriginFrecenciesRunnable::Run() { NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr selectStmt; - rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING("SELECT 1 " - "FROM moz_origins " - "WHERE frecency < 0 " - "LIMIT 1 "), + rv = mDBConn->CreateStatement(nsLiteralCString("SELECT 1 " + "FROM moz_origins " + "WHERE frecency < 0 " + "LIMIT 1 "), getter_AddRefs(selectStmt)); NS_ENSURE_SUCCESS(rv, rv); bool hasResult = false; @@ -2404,19 +2366,19 @@ nsresult Database::MigrateV52Up() { // Set all origin frecencies to -1 so that MigrateV52OriginFrecenciesRunnable // will migrate them. - nsresult rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("UPDATE moz_origins SET frecency = -1 ")); + nsresult rv = + mMainConn->ExecuteSimpleSQL("UPDATE moz_origins SET frecency = -1 "_ns); NS_ENSURE_SUCCESS(rv, rv); // This migration also renames these moz_meta keys that keep track of frecency // stats. (That happens when stats are recalculated.) Delete the old ones. - rv = mMainConn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_meta " - "WHERE key IN ( " - "'frecency_count', " - "'frecency_sum', " - "'frecency_sum_of_squares' " - ") ")); + rv = + mMainConn->ExecuteSimpleSQL(nsLiteralCString("DELETE FROM moz_meta " + "WHERE key IN ( " + "'frecency_count', " + "'frecency_sum', " + "'frecency_sum_of_squares' " + ") ")); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -2424,9 +2386,8 @@ nsresult Database::MigrateV52Up() { nsresult Database::MigrateV53Up() { nsCOMPtr stmt; - nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT 1 FROM moz_items_annos"), - getter_AddRefs(stmt)); + nsresult rv = mMainConn->CreateStatement("SELECT 1 FROM moz_items_annos"_ns, + getter_AddRefs(stmt)); if (NS_FAILED(rv)) { // Likely we removed the table. return NS_OK; @@ -2434,20 +2395,20 @@ nsresult Database::MigrateV53Up() { // Remove all item annotations but SYNC_PARENT_ANNO. rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "DELETE FROM moz_items_annos " "WHERE anno_attribute_id NOT IN ( " " SELECT id FROM moz_anno_attributes WHERE name = :anno_name " ") "), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), - NS_LITERAL_CSTRING(SYNC_PARENT_ANNO)); + rv = stmt->BindUTF8StringByName("anno_name"_ns, + nsLiteralCString(SYNC_PARENT_ANNO)); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); - rv = mMainConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + rv = mMainConn->ExecuteSimpleSQL(nsLiteralCString( "DELETE FROM moz_anno_attributes WHERE id IN ( " " SELECT id FROM moz_anno_attributes " " EXCEPT " @@ -2484,12 +2445,12 @@ nsresult Database::ConvertOldStyleQuery(nsCString& aURL) { // We have the folder's ID, now to find its GUID. nsCOMPtr stmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT guid FROM moz_bookmarks " - "WHERE id = :itemId "), + nsLiteralCString("SELECT guid FROM moz_bookmarks " + "WHERE id = :itemId "), getter_AddRefs(stmt)); if (NS_FAILED(rv)) return rv; - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("itemId"), itemId); + rv = stmt->BindInt64ByName("itemId"_ns, itemId); if (NS_FAILED(rv)) return rv; bool hasMore = false; @@ -2498,28 +2459,27 @@ nsresult Database::ConvertOldStyleQuery(nsCString& aURL) { if (NS_FAILED(rv)) return rv; } } else if (kvp.value.EqualsLiteral("PLACES_ROOT")) { - guid = NS_LITERAL_CSTRING(ROOT_GUID); + guid = nsLiteralCString(ROOT_GUID); } else if (kvp.value.EqualsLiteral("BOOKMARKS_MENU")) { - guid = NS_LITERAL_CSTRING(MENU_ROOT_GUID); + guid = nsLiteralCString(MENU_ROOT_GUID); } else if (kvp.value.EqualsLiteral("TAGS")) { - guid = NS_LITERAL_CSTRING(TAGS_ROOT_GUID); + guid = nsLiteralCString(TAGS_ROOT_GUID); } else if (kvp.value.EqualsLiteral("UNFILED_BOOKMARKS")) { - guid = NS_LITERAL_CSTRING(UNFILED_ROOT_GUID); + guid = nsLiteralCString(UNFILED_ROOT_GUID); } else if (kvp.value.EqualsLiteral("TOOLBAR")) { - guid = NS_LITERAL_CSTRING(TOOLBAR_ROOT_GUID); + guid = nsLiteralCString(TOOLBAR_ROOT_GUID); } else if (kvp.value.EqualsLiteral("MOBILE_BOOKMARKS")) { - guid = NS_LITERAL_CSTRING(MOBILE_ROOT_GUID); + guid = nsLiteralCString(MOBILE_ROOT_GUID); } QueryKeyValuePair* newPair; if (guid.IsEmpty()) { // This is invalid, so we'll change this key/value pair to something else // so that the query remains a valid url. - newPair = new QueryKeyValuePair(NS_LITERAL_CSTRING("invalidOldParentId"), - kvp.value); + newPair = new QueryKeyValuePair("invalidOldParentId"_ns, kvp.value); invalid = true; } else { - newPair = new QueryKeyValuePair(NS_LITERAL_CSTRING("parent"), guid); + newPair = new QueryKeyValuePair("parent"_ns, guid); } // XXX(Bug 1631371) Check if this should use a fallible operation as it // pretended earlier. @@ -2529,8 +2489,7 @@ nsresult Database::ConvertOldStyleQuery(nsCString& aURL) { if (invalid) { // One or more of the folders don't exist, replace with an empty query. - newTokens.AppendElement(QueryKeyValuePair( - NS_LITERAL_CSTRING("excludeItems"), NS_LITERAL_CSTRING("1"))); + newTokens.AppendElement(QueryKeyValuePair("excludeItems"_ns, "1"_ns)); } TokensToQueryString(newTokens, aURL); @@ -2544,7 +2503,7 @@ int64_t Database::CreateMobileRoot() { // example, if the user downgraded to an earlier release channel). nsCOMPtr createStmt; nsresult rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "INSERT OR IGNORE INTO moz_bookmarks " "(type, title, dateAdded, lastModified, guid, position, parent) " "SELECT :item_type, :item_title, :timestamp, :timestamp, :guid, " @@ -2554,17 +2513,16 @@ int64_t Database::CreateMobileRoot() { getter_AddRefs(createStmt)); if (NS_FAILED(rv)) return -1; - rv = createStmt->BindInt32ByName(NS_LITERAL_CSTRING("item_type"), + rv = createStmt->BindInt32ByName("item_type"_ns, nsINavBookmarksService::TYPE_FOLDER); if (NS_FAILED(rv)) return -1; - rv = createStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_title"), - NS_LITERAL_CSTRING(MOBILE_ROOT_TITLE)); + rv = createStmt->BindUTF8StringByName("item_title"_ns, + nsLiteralCString(MOBILE_ROOT_TITLE)); if (NS_FAILED(rv)) return -1; - rv = createStmt->BindInt64ByName(NS_LITERAL_CSTRING("timestamp"), - RoundedPRNow()); + rv = createStmt->BindInt64ByName("timestamp"_ns, RoundedPRNow()); if (NS_FAILED(rv)) return -1; - rv = createStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), - NS_LITERAL_CSTRING(MOBILE_ROOT_GUID)); + rv = createStmt->BindUTF8StringByName("guid"_ns, + nsLiteralCString(MOBILE_ROOT_GUID)); if (NS_FAILED(rv)) return -1; rv = createStmt->Execute(); @@ -2574,12 +2532,12 @@ int64_t Database::CreateMobileRoot() { // root might already exist, and we ignore on conflict. nsCOMPtr findIdStmt; rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT id FROM moz_bookmarks WHERE guid = :guid"), + "SELECT id FROM moz_bookmarks WHERE guid = :guid"_ns, getter_AddRefs(findIdStmt)); if (NS_FAILED(rv)) return -1; - rv = findIdStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), - NS_LITERAL_CSTRING(MOBILE_ROOT_GUID)); + rv = findIdStmt->BindUTF8StringByName("guid"_ns, + nsLiteralCString(MOBILE_ROOT_GUID)); if (NS_FAILED(rv)) return -1; bool hasResult = false; @@ -2617,17 +2575,17 @@ void Database::Shutdown() { // Sanity check for missing guids. nsresult rv = - mMainConn->CreateStatement(NS_LITERAL_CSTRING("SELECT 1 " - "FROM moz_places " - "WHERE guid IS NULL "), + mMainConn->CreateStatement(nsLiteralCString("SELECT 1 " + "FROM moz_places " + "WHERE guid IS NULL "), getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = stmt->ExecuteStep(&hasResult); MOZ_ASSERT(NS_SUCCEEDED(rv)); MOZ_ASSERT(!hasResult, "Found a page without a GUID!"); - rv = mMainConn->CreateStatement(NS_LITERAL_CSTRING("SELECT 1 " - "FROM moz_bookmarks " - "WHERE guid IS NULL "), + rv = mMainConn->CreateStatement(nsLiteralCString("SELECT 1 " + "FROM moz_bookmarks " + "WHERE guid IS NULL "), getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = stmt->ExecuteStep(&hasResult); @@ -2637,7 +2595,7 @@ void Database::Shutdown() { // Sanity check for unrounded dateAdded and lastModified values (bug // 1107308). rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT 1 " "FROM moz_bookmarks " "WHERE dateAdded % 1000 > 0 OR lastModified % 1000 > 0 LIMIT 1"), @@ -2649,8 +2607,7 @@ void Database::Shutdown() { // Sanity check url_hash rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT 1 FROM moz_places WHERE url_hash = 0"), - getter_AddRefs(stmt)); + "SELECT 1 FROM moz_places WHERE url_hash = 0"_ns, getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = stmt->ExecuteStep(&hasResult); MOZ_ASSERT(NS_SUCCEEDED(rv)); @@ -2658,7 +2615,7 @@ void Database::Shutdown() { // Sanity check unique urls rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT 1 FROM moz_places GROUP BY url HAVING count(*) > 1 "), getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); @@ -2668,8 +2625,7 @@ void Database::Shutdown() { // Sanity check NULL urls rv = mMainConn->CreateStatement( - NS_LITERAL_CSTRING("SELECT 1 FROM moz_places WHERE url ISNULL "), - getter_AddRefs(stmt)); + "SELECT 1 FROM moz_places WHERE url ISNULL "_ns, getter_AddRefs(stmt)); MOZ_ASSERT(NS_SUCCEEDED(rv)); rv = stmt->ExecuteStep(&hasResult); MOZ_ASSERT(NS_SUCCEEDED(rv)); @@ -2691,8 +2647,7 @@ void Database::Shutdown() { // performance across restarts. nsCOMPtr ps; MOZ_ALWAYS_SUCCEEDS(mMainConn->ExecuteSimpleSQLAsync( - NS_LITERAL_CSTRING("PRAGMA optimize(0x02)"), nullptr, - getter_AddRefs(ps))); + "PRAGMA optimize(0x02)"_ns, nullptr, getter_AddRefs(ps))); (void)mMainConn->AsyncClose(connectionShutdown); mMainConn = nullptr; diff --git a/toolkit/components/places/FaviconHelpers.cpp b/toolkit/components/places/FaviconHelpers.cpp index 54069882898b..8bd2b7ea79d9 100644 --- a/toolkit/components/places/FaviconHelpers.cpp +++ b/toolkit/components/places/FaviconHelpers.cpp @@ -88,8 +88,7 @@ nsresult FetchPageInfo(const RefPtr& aDB, PageData& _page) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), _page.spec); + nsresult rv = URIBinder::Bind(stmt, "page_url"_ns, _page.spec); NS_ENSURE_SUCCESS(rv, rv); bool hasResult; @@ -185,8 +184,7 @@ nsresult SetIconInfo(const RefPtr& aDB, IconData& aIcon, "AND icon_url = :url "); NS_ENSURE_STATE(selectStmt); mozStorageStatementScoper scoper(selectStmt); - nsresult rv = - URIBinder::Bind(selectStmt, NS_LITERAL_CSTRING("url"), aIcon.spec); + nsresult rv = URIBinder::Bind(selectStmt, "url"_ns, aIcon.spec); NS_ENSURE_SUCCESS(rv, rv); std::deque ids; bool hasResult = false; @@ -233,19 +231,15 @@ nsresult SetIconInfo(const RefPtr& aDB, IconData& aIcon, int64_t id = ids.front(); ids.pop_front(); mozStorageStatementScoper scoper(updateStmt); - rv = updateStmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), id); + rv = updateStmt->BindInt64ByName("id"_ns, id); NS_ENSURE_SUCCESS(rv, rv); - rv = updateStmt->BindInt32ByName(NS_LITERAL_CSTRING("width"), - payload.width); + rv = updateStmt->BindInt32ByName("width"_ns, payload.width); NS_ENSURE_SUCCESS(rv, rv); - rv = updateStmt->BindInt64ByName(NS_LITERAL_CSTRING("expire"), - aIcon.expiration / 1000); + rv = updateStmt->BindInt64ByName("expire"_ns, aIcon.expiration / 1000); NS_ENSURE_SUCCESS(rv, rv); - rv = updateStmt->BindInt32ByName(NS_LITERAL_CSTRING("root"), - aIcon.rootIcon); + rv = updateStmt->BindInt32ByName("root"_ns, aIcon.rootIcon); NS_ENSURE_SUCCESS(rv, rv); - rv = updateStmt->BindBlobByName(NS_LITERAL_CSTRING("data"), - TO_INTBUFFER(payload.data), + rv = updateStmt->BindBlobByName("data"_ns, TO_INTBUFFER(payload.data), payload.data.Length()); NS_ENSURE_SUCCESS(rv, rv); rv = updateStmt->Execute(); @@ -255,20 +249,16 @@ nsresult SetIconInfo(const RefPtr& aDB, IconData& aIcon, } else { // Insert a new entry. mozStorageStatementScoper scoper(insertStmt); - rv = URIBinder::Bind(insertStmt, NS_LITERAL_CSTRING("url"), aIcon.spec); + rv = URIBinder::Bind(insertStmt, "url"_ns, aIcon.spec); NS_ENSURE_SUCCESS(rv, rv); - rv = insertStmt->BindInt32ByName(NS_LITERAL_CSTRING("width"), - payload.width); + rv = insertStmt->BindInt32ByName("width"_ns, payload.width); NS_ENSURE_SUCCESS(rv, rv); - rv = insertStmt->BindInt32ByName(NS_LITERAL_CSTRING("root"), - aIcon.rootIcon); + rv = insertStmt->BindInt32ByName("root"_ns, aIcon.rootIcon); NS_ENSURE_SUCCESS(rv, rv); - rv = insertStmt->BindInt64ByName(NS_LITERAL_CSTRING("expire"), - aIcon.expiration / 1000); + rv = insertStmt->BindInt64ByName("expire"_ns, aIcon.expiration / 1000); NS_ENSURE_SUCCESS(rv, rv); - rv = insertStmt->BindBlobByName(NS_LITERAL_CSTRING("data"), - TO_INTBUFFER(payload.data), + rv = insertStmt->BindBlobByName("data"_ns, TO_INTBUFFER(payload.data), payload.data.Length()); NS_ENSURE_SUCCESS(rv, rv); rv = insertStmt->Execute(); @@ -327,8 +317,7 @@ nsresult FetchIconInfo(const RefPtr& aDB, uint16_t aPreferredWidth, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - DebugOnly rv = - URIBinder::Bind(stmt, NS_LITERAL_CSTRING("url"), _icon.spec); + DebugOnly rv = URIBinder::Bind(stmt, "url"_ns, _icon.spec); MOZ_ASSERT(NS_SUCCEEDED(rv)); bool hasResult = false; @@ -411,17 +400,16 @@ nsresult FetchIconPerSpec(const RefPtr& aDB, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("url"), aPageSpec); + nsresult rv = URIBinder::Bind(stmt, "url"_ns, aPageSpec); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString rootIconFixedUrl(aPageHost); if (!rootIconFixedUrl.IsEmpty()) { rootIconFixedUrl.AppendLiteral("/favicon.ico"); } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("root_icon_url"), - rootIconFixedUrl); + rv = stmt->BindUTF8StringByName("root_icon_url"_ns, rootIconFixedUrl); NS_ENSURE_SUCCESS(rv, rv); int32_t hashIdx = PromiseFlatCString(aPageSpec).RFind("#"); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("hash_idx"), hashIdx + 1); + rv = stmt->BindInt32ByName("hash_idx"_ns, hashIdx + 1); NS_ENSURE_SUCCESS(rv, rv); // Return the biggest icon close to the preferred width. It may be bigger @@ -862,7 +850,7 @@ AsyncAssociateIconToPage::Run() { ") AND page_id = :page_id "); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), mPage.id); + rv = stmt->BindInt64ByName("page_id"_ns, mPage.id); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -891,7 +879,7 @@ AsyncAssociateIconToPage::Run() { "VALUES (:page_url, hash(:page_url)) "); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), mPage.spec); + rv = URIBinder::Bind(stmt, "page_url"_ns, mPage.spec); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -913,9 +901,9 @@ AsyncAssociateIconToPage::Run() { for (const auto& payload : mIcon.payloads) { mozStorageStatementScoper scoper(stmt); nsCOMPtr params; - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), mPage.spec); + rv = URIBinder::Bind(stmt, "page_url"_ns, mPage.spec); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("icon_id"), payload.id); + rv = stmt->BindInt64ByName("icon_id"_ns, payload.id); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -1154,7 +1142,7 @@ FetchAndConvertUnsupportedPayloads::Run() { nsCOMPtr stmt; nsresult rv = mDB->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id, width, data FROM moz_icons WHERE typeof(width) = 'text' " "ORDER BY id ASC " "LIMIT 200 "), @@ -1207,11 +1195,11 @@ FetchAndConvertUnsupportedPayloads::Run() { // We're done. Remove any leftovers. rv = mDB->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_icons WHERE typeof(width) = 'text'")); + "DELETE FROM moz_icons WHERE typeof(width) = 'text'"_ns); NS_ENSURE_SUCCESS(rv, rv); // Run a one-time VACUUM of places.sqlite, since we removed a lot from it. // It may cause jank, but not doing it could cause dataloss due to expiration. - rv = mDB->ExecuteSimpleSQL(NS_LITERAL_CSTRING("VACUUM")); + rv = mDB->ExecuteSimpleSQL("VACUUM"_ns); NS_ENSURE_SUCCESS(rv, rv); // Re-dispatch to the main-thread to flip the conversion pref. @@ -1328,16 +1316,16 @@ nsresult FetchAndConvertUnsupportedPayloads::StorePayload( NS_ENSURE_STATE(mDB); nsCOMPtr stmt; nsresult rv = mDB->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "UPDATE moz_icons SET data = :data, width = :width WHERE id = :id"), getter_AddRefs(stmt)); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), aId); + rv = stmt->BindInt64ByName("id"_ns, aId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("width"), aWidth); + rv = stmt->BindInt32ByName("width"_ns, aWidth); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindBlobByName(NS_LITERAL_CSTRING("data"), TO_INTBUFFER(aPayload), + rv = stmt->BindBlobByName("data"_ns, TO_INTBUFFER(aPayload), aPayload.Length()); NS_ENSURE_SUCCESS(rv, rv); @@ -1407,7 +1395,7 @@ AsyncCopyFavicons::Run() { "VALUES (:page_url, hash(:page_url)) "); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), mToPage.spec); + rv = URIBinder::Bind(stmt, "page_url"_ns, mToPage.spec); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -1425,9 +1413,9 @@ AsyncCopyFavicons::Run() { "hash(:url) AND page_url = :url) "); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), mToPage.id); + rv = stmt->BindInt64ByName("id"_ns, mToPage.id); NS_ENSURE_SUCCESS(rv, rv); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("url"), mFromPage.spec); + rv = URIBinder::Bind(stmt, "url"_ns, mFromPage.spec); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); diff --git a/toolkit/components/places/Helpers.cpp b/toolkit/components/places/Helpers.cpp index 179b4d964c1d..f7a2c55ffc92 100644 --- a/toolkit/components/places/Helpers.cpp +++ b/toolkit/components/places/Helpers.cpp @@ -363,7 +363,7 @@ nsresult TokenizeQueryString(const nsACString& aQuery, void TokensToQueryString(const nsTArray& aTokens, nsACString& aQuery) { - aQuery = NS_LITERAL_CSTRING("place:"); + aQuery = "place:"_ns; for (uint32_t i = 0; i < aTokens.Length(); i++) { if (i > 0) { aQuery.Append("&"); diff --git a/toolkit/components/places/History.cpp b/toolkit/components/places/History.cpp index ee187c64423a..ead5ce129fa0 100644 --- a/toolkit/components/places/History.cpp +++ b/toolkit/components/places/History.cpp @@ -61,8 +61,7 @@ namespace places { // Observer event fired after a visit has been registered in the DB. #define URI_VISIT_SAVED "uri-visit-saved" -#define DESTINATIONFILEURI_ANNO \ - NS_LITERAL_CSTRING("downloads/destinationFileURI") +#define DESTINATIONFILEURI_ANNO "downloads/destinationFileURI"_ns //////////////////////////////////////////////////////////////////////////////// //// VisitData @@ -1120,20 +1119,17 @@ class InsertVisitedURIs final : public Runnable { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), _place.placeId); + rv = stmt->BindInt64ByName("page_id"_ns, _place.placeId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("from_visit"), - _place.referrerVisitId); + rv = stmt->BindInt64ByName("from_visit"_ns, _place.referrerVisitId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("visit_date"), - _place.visitTime); + rv = stmt->BindInt64ByName("visit_date"_ns, _place.visitTime); NS_ENSURE_SUCCESS(rv, rv); uint32_t transitionType = _place.transitionType; MOZ_ASSERT(transitionType >= nsINavHistoryService::TRANSITION_LINK && transitionType <= nsINavHistoryService::TRANSITION_RELOAD, "Invalid transition type!"); - rv = - stmt->BindInt32ByName(NS_LITERAL_CSTRING("visit_type"), transitionType); + rv = stmt->BindInt32ByName("visit_type"_ns, transitionType); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1178,10 +1174,10 @@ class InsertVisitedURIs final : public Runnable { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), aPlace.placeId); + rv = stmt->BindInt64ByName("page_id"_ns, aPlace.placeId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("redirect"), - aPlace.useFrecencyRedirectBonus); + rv = + stmt->BindInt32ByName("redirect"_ns, aPlace.useFrecencyRedirectBonus); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1198,7 +1194,7 @@ class InsertVisitedURIs final : public Runnable { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), aPlace.placeId); + rv = stmt->BindInt64ByName("page_id"_ns, aPlace.placeId); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1290,14 +1286,14 @@ class SetPageTitle : public Runnable { { mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), mPlace.placeId); + rv = stmt->BindInt64ByName("page_id"_ns, mPlace.placeId); NS_ENSURE_SUCCESS(rv, rv); // Empty strings should clear the title, just like // nsNavHistory::SetPageTitle. if (mPlace.title.IsEmpty()) { - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("page_title")); + rv = stmt->BindNullByName("page_title"_ns); } else { - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("page_title"), + rv = stmt->BindStringByName("page_title"_ns, StringHead(mPlace.title, TITLE_LENGTH_MAX)); } NS_ENSURE_SUCCESS(rv, rv); @@ -1434,9 +1430,9 @@ class ConcurrentStatementsHolder final : public mozIStorageCompletionCallback { if (!mIsVisitedStatement) { (void)mReadOnlyDBConn->CreateAsyncStatement( - NS_LITERAL_CSTRING("SELECT 1 FROM moz_places h " - "WHERE url_hash = hash(?1) AND url = ?1 AND " - "last_visit_date NOTNULL "), + nsLiteralCString("SELECT 1 FROM moz_places h " + "WHERE url_hash = hash(?1) AND url = ?1 AND " + "last_visit_date NOTNULL "), getter_AddRefs(mIsVisitedStatement)); MOZ_ASSERT(mIsVisitedStatement); auto queries = std::move(mVisitedQueries); @@ -1513,34 +1509,33 @@ nsresult History::InsertPlace(VisitData& aPlace, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - stmt->BindStringByName(NS_LITERAL_CSTRING("rev_host"), aPlace.revHost); + nsresult rv = stmt->BindStringByName("rev_host"_ns, aPlace.revHost); NS_ENSURE_SUCCESS(rv, rv); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("url"), aPlace.spec); + rv = URIBinder::Bind(stmt, "url"_ns, aPlace.spec); NS_ENSURE_SUCCESS(rv, rv); nsString title = aPlace.title; // Empty strings should have no title, just like nsNavHistory::SetPageTitle. if (title.IsEmpty()) { - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("title")); + rv = stmt->BindNullByName("title"_ns); } else { title.Assign(StringHead(aPlace.title, TITLE_LENGTH_MAX)); - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("title"), title); + rv = stmt->BindStringByName("title"_ns, title); } NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("typed"), aPlace.typed); + rv = stmt->BindInt32ByName("typed"_ns, aPlace.typed); NS_ENSURE_SUCCESS(rv, rv); // When inserting a page for a first visit that should not appear in // autocomplete, for example an error page, use a zero frecency. int32_t frecency = aPlace.shouldUpdateFrecency ? aPlace.frecency : 0; - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("frecency"), frecency); + rv = stmt->BindInt32ByName("frecency"_ns, frecency); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("hidden"), aPlace.hidden); + rv = stmt->BindInt32ByName("hidden"_ns, aPlace.hidden); NS_ENSURE_SUCCESS(rv, rv); if (aPlace.guid.IsVoid()) { rv = GenerateGUID(aPlace.guid); NS_ENSURE_SUCCESS(rv, rv); } - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aPlace.guid); + rv = stmt->BindUTF8StringByName("guid"_ns, aPlace.guid); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -1587,20 +1582,20 @@ nsresult History::UpdatePlace(const VisitData& aPlace) { if (!titleIsVoid) { // An empty string clears the title. if (aPlace.title.IsEmpty()) { - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("title")); + rv = stmt->BindNullByName("title"_ns); } else { - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("title"), + rv = stmt->BindStringByName("title"_ns, StringHead(aPlace.title, TITLE_LENGTH_MAX)); } NS_ENSURE_SUCCESS(rv, rv); } - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("typed"), aPlace.typed); + rv = stmt->BindInt32ByName("typed"_ns, aPlace.typed); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("hidden"), aPlace.hidden); + rv = stmt->BindInt32ByName("hidden"_ns, aPlace.hidden); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aPlace.guid); + rv = stmt->BindUTF8StringByName("guid"_ns, aPlace.guid); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), aPlace.placeId); + rv = stmt->BindInt64ByName("page_id"_ns, aPlace.placeId); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -1629,7 +1624,7 @@ nsresult History::FetchPageInfo(VisitData& _place, bool* _exists) { "WHERE url_hash = hash(:page_url) AND url = :page_url "); NS_ENSURE_STATE(stmt); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), _place.spec); + rv = URIBinder::Bind(stmt, "page_url"_ns, _place.spec); NS_ENSURE_SUCCESS(rv, rv); } else { stmt = GetStatement( @@ -1642,7 +1637,7 @@ nsresult History::FetchPageInfo(VisitData& _place, bool* _exists) { "WHERE guid = :guid "); NS_ENSURE_STATE(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), _place.guid); + rv = stmt->BindUTF8StringByName("guid"_ns, _place.guid); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/toolkit/components/places/PageIconProtocolHandler.cpp b/toolkit/components/places/PageIconProtocolHandler.cpp index 237d682cfef3..43f59da29b60 100644 --- a/toolkit/components/places/PageIconProtocolHandler.cpp +++ b/toolkit/components/places/PageIconProtocolHandler.cpp @@ -72,7 +72,7 @@ static nsresult MakeDefaultFaviconChannel(nsIURI* aURI, nsILoadInfo* aLoadInfo, getter_AddRefs(chan)); NS_ENSURE_SUCCESS(rv, rv); chan->SetOriginalURI(aURI); - chan->SetContentType(NS_LITERAL_CSTRING(FAVICON_DEFAULT_MIMETYPE)); + chan->SetContentType(nsLiteralCString(FAVICON_DEFAULT_MIMETYPE)); chan.forget(aOutChannel); return NS_OK; } @@ -90,8 +90,7 @@ static nsresult StreamDefaultFavicon(nsIURI* aURI, nsILoadInfo* aLoadInfo, aOutputStream, observer); NS_ENSURE_SUCCESS(rv, rv); - aOriginalChannel->SetContentType( - NS_LITERAL_CSTRING(FAVICON_DEFAULT_MIMETYPE)); + aOriginalChannel->SetContentType(nsLiteralCString(FAVICON_DEFAULT_MIMETYPE)); nsCOMPtr defaultIconChannel; rv = MakeDefaultFaviconChannel(aURI, aLoadInfo, getter_AddRefs(defaultIconChannel)); @@ -152,7 +151,7 @@ NS_IMPL_ISUPPORTS(PageIconProtocolHandler, nsIProtocolHandler, nsISupportsWeakReference); NS_IMETHODIMP PageIconProtocolHandler::GetScheme(nsACString& aScheme) { - aScheme.Assign(NS_LITERAL_CSTRING("page-icon")); + aScheme.Assign("page-icon"_ns); return NS_OK; } diff --git a/toolkit/components/places/SQLFunctions.cpp b/toolkit/components/places/SQLFunctions.cpp index 4b8ab7e71908..cd09e8b7db32 100644 --- a/toolkit/components/places/SQLFunctions.cpp +++ b/toolkit/components/places/SQLFunctions.cpp @@ -372,8 +372,8 @@ namespace places { nsresult MatchAutoCompleteFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new MatchAutoCompleteFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("autocomplete_match"), kArgIndexLength, function); + nsresult rv = aDBConn->CreateFunction("autocomplete_match"_ns, + kArgIndexLength, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -398,11 +398,11 @@ nsDependentCSubstring MatchAutoCompleteFunction::fixupURISpec( if (aMatchBehavior == mozIPlacesAutoComplete::MATCH_ANYWHERE_UNMODIFIED) return fixedSpec; - if (StringBeginsWith(fixedSpec, NS_LITERAL_CSTRING("http://"))) { + if (StringBeginsWith(fixedSpec, "http://"_ns)) { fixedSpec.Rebind(fixedSpec, 7); - } else if (StringBeginsWith(fixedSpec, NS_LITERAL_CSTRING("https://"))) { + } else if (StringBeginsWith(fixedSpec, "https://"_ns)) { fixedSpec.Rebind(fixedSpec, 8); - } else if (StringBeginsWith(fixedSpec, NS_LITERAL_CSTRING("ftp://"))) { + } else if (StringBeginsWith(fixedSpec, "ftp://"_ns)) { fixedSpec.Rebind(fixedSpec, 6); } @@ -462,9 +462,8 @@ MatchAutoCompleteFunction::OnFunctionCall(mozIStorageValueArray* aArguments, // We only want to filter javascript: URLs if we are not supposed to search // for them, and the search does not start with "javascript:". if (matchBehavior != mozIPlacesAutoComplete::MATCH_ANYWHERE_UNMODIFIED && - StringBeginsWith(url, NS_LITERAL_CSTRING("javascript:")) && - !HAS_BEHAVIOR(JAVASCRIPT) && - !StringBeginsWith(searchString, NS_LITERAL_CSTRING("javascript:"))) { + StringBeginsWith(url, "javascript:"_ns) && !HAS_BEHAVIOR(JAVASCRIPT) && + !StringBeginsWith(searchString, "javascript:"_ns)) { NS_ADDREF(*_result = mCachedZero); return NS_OK; } @@ -551,8 +550,7 @@ MatchAutoCompleteFunction::OnFunctionCall(mozIStorageValueArray* aArguments, nsresult CalculateFrecencyFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new CalculateFrecencyFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("calculate_frecency"), -1, function); + nsresult rv = aDBConn->CreateFunction("calculate_frecency"_ns, -1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -608,7 +606,7 @@ CalculateFrecencyFunction::OnFunctionCall(mozIStorageValueArray* aArguments, NS_ENSURE_STATE(getPageInfo); mozStorageStatementScoper infoScoper(getPageInfo); - rv = getPageInfo->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), pageId); + rv = getPageInfo->BindInt64ByName("page_id"_ns, pageId); NS_ENSURE_SUCCESS(rv, rv); bool hasResult = false; @@ -636,7 +634,7 @@ CalculateFrecencyFunction::OnFunctionCall(mozIStorageValueArray* aArguments, "%d AND %d ", nsINavHistoryService::TRANSITION_REDIRECT_PERMANENT, nsINavHistoryService::TRANSITION_REDIRECT_TEMPORARY); nsCOMPtr getVisits = DB->GetStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "/* do not warn (bug 659740 - SQLite may ignore index if few " "visits exist) */" "SELECT " @@ -648,18 +646,18 @@ CalculateFrecencyFunction::OnFunctionCall(mozIStorageValueArray* aArguments, "LEFT JOIN moz_historyvisits origin ON origin.id = v.from_visit " "AND v.visit_type BETWEEN ") + redirectsTransitionFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( "LEFT JOIN moz_historyvisits target ON v.id = target.from_visit " "AND target.visit_type BETWEEN ") + redirectsTransitionFragment + - NS_LITERAL_CSTRING("WHERE v.place_id = :page_id " - "ORDER BY v.visit_date DESC " - "LIMIT :max_visits ")); + nsLiteralCString("WHERE v.place_id = :page_id " + "ORDER BY v.visit_date DESC " + "LIMIT :max_visits ")); NS_ENSURE_STATE(getVisits); mozStorageStatementScoper visitsScoper(getVisits); - rv = getVisits->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), pageId); + rv = getVisits->BindInt64ByName("page_id"_ns, pageId); NS_ENSURE_SUCCESS(rv, rv); - rv = getVisits->BindInt32ByName(NS_LITERAL_CSTRING("max_visits"), + rv = getVisits->BindInt32ByName("max_visits"_ns, history->GetNumVisitsForFrecency()); NS_ENSURE_SUCCESS(rv, rv); @@ -761,8 +759,7 @@ CalculateFrecencyFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult GenerateGUIDFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new GenerateGUIDFunction(); - nsresult rv = - aDBConn->CreateFunction(NS_LITERAL_CSTRING("generate_guid"), 0, function); + nsresult rv = aDBConn->CreateFunction("generate_guid"_ns, 0, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -787,8 +784,7 @@ GenerateGUIDFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult IsValidGUIDFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new IsValidGUIDFunction(); - return aDBConn->CreateFunction(NS_LITERAL_CSTRING("is_valid_guid"), 1, - function); + return aDBConn->CreateFunction("is_valid_guid"_ns, 1, function); } NS_IMPL_ISUPPORTS(IsValidGUIDFunction, mozIStorageFunction) @@ -814,8 +810,7 @@ IsValidGUIDFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult GetUnreversedHostFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new GetUnreversedHostFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("get_unreversed_host"), 1, function); + nsresult rv = aDBConn->CreateFunction("get_unreversed_host"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -852,8 +847,7 @@ GetUnreversedHostFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult FixupURLFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new FixupURLFunction(); - nsresult rv = - aDBConn->CreateFunction(NS_LITERAL_CSTRING("fixup_url"), 1, function); + nsresult rv = aDBConn->CreateFunction("fixup_url"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -872,15 +866,15 @@ FixupURLFunction::OnFunctionCall(mozIStorageValueArray* aArguments, RefPtr result = new nsVariant(); - if (StringBeginsWith(src, NS_LITERAL_STRING("http://"))) + if (StringBeginsWith(src, u"http://"_ns)) src.Cut(0, 7); - else if (StringBeginsWith(src, NS_LITERAL_STRING("https://"))) + else if (StringBeginsWith(src, u"https://"_ns)) src.Cut(0, 8); - else if (StringBeginsWith(src, NS_LITERAL_STRING("ftp://"))) + else if (StringBeginsWith(src, u"ftp://"_ns)) src.Cut(0, 6); // Remove common URL hostname prefixes - if (StringBeginsWith(src, NS_LITERAL_STRING("www."))) { + if (StringBeginsWith(src, u"www."_ns)) { src.Cut(0, 4); } @@ -896,8 +890,7 @@ FixupURLFunction::OnFunctionCall(mozIStorageValueArray* aArguments, nsresult FrecencyNotificationFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new FrecencyNotificationFunction(); - nsresult rv = aDBConn->CreateFunction(NS_LITERAL_CSTRING("notify_frecency"), - 5, function); + nsresult rv = aDBConn->CreateFunction("notify_frecency"_ns, 5, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -945,8 +938,8 @@ FrecencyNotificationFunction::OnFunctionCall(mozIStorageValueArray* aArgs, nsresult StoreLastInsertedIdFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new StoreLastInsertedIdFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("store_last_inserted_id"), 2, function); + nsresult rv = + aDBConn->CreateFunction("store_last_inserted_id"_ns, 2, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -994,8 +987,7 @@ StoreLastInsertedIdFunction::OnFunctionCall(mozIStorageValueArray* aArgs, /* static */ nsresult GetQueryParamFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new GetQueryParamFunction(); - return aDBConn->CreateFunction(NS_LITERAL_CSTRING("get_query_param"), 2, - function); + return aDBConn->CreateFunction("get_query_param"_ns, 2, function); } NS_IMPL_ISUPPORTS(GetQueryParamFunction, mozIStorageFunction) @@ -1025,7 +1017,7 @@ GetQueryParamFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult HashFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new HashFunction(); - return aDBConn->CreateFunction(NS_LITERAL_CSTRING("hash"), -1, function); + return aDBConn->CreateFunction("hash"_ns, -1, function); } NS_IMPL_ISUPPORTS(HashFunction, mozIStorageFunction) @@ -1065,8 +1057,7 @@ HashFunction::OnFunctionCall(mozIStorageValueArray* aArguments, /* static */ nsresult GetPrefixFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new GetPrefixFunction(); - nsresult rv = - aDBConn->CreateFunction(NS_LITERAL_CSTRING("get_prefix"), 1, function); + nsresult rv = aDBConn->CreateFunction("get_prefix"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1098,8 +1089,7 @@ GetPrefixFunction::OnFunctionCall(mozIStorageValueArray* aArgs, /* static */ nsresult GetHostAndPortFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new GetHostAndPortFunction(); - nsresult rv = aDBConn->CreateFunction(NS_LITERAL_CSTRING("get_host_and_port"), - 1, function); + nsresult rv = aDBConn->CreateFunction("get_host_and_port"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1136,8 +1126,8 @@ nsresult StripPrefixAndUserinfoFunction::create( mozIStorageConnection* aDBConn) { RefPtr function = new StripPrefixAndUserinfoFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("strip_prefix_and_userinfo"), 1, function); + nsresult rv = + aDBConn->CreateFunction("strip_prefix_and_userinfo"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1172,8 +1162,7 @@ StripPrefixAndUserinfoFunction::OnFunctionCall(mozIStorageValueArray* aArgs, nsresult IsFrecencyDecayingFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new IsFrecencyDecayingFunction(); - nsresult rv = aDBConn->CreateFunction( - NS_LITERAL_CSTRING("is_frecency_decaying"), 0, function); + nsresult rv = aDBConn->CreateFunction("is_frecency_decaying"_ns, 0, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -1207,8 +1196,7 @@ IsFrecencyDecayingFunction::OnFunctionCall(mozIStorageValueArray* aArgs, /* static */ nsresult SqrtFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new SqrtFunction(); - nsresult rv = - aDBConn->CreateFunction(NS_LITERAL_CSTRING("sqrt"), 1, function); + nsresult rv = aDBConn->CreateFunction("sqrt"_ns, 1, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } @@ -1241,8 +1229,7 @@ SqrtFunction::OnFunctionCall(mozIStorageValueArray* aArgs, /* static */ nsresult NoteSyncChangeFunction::create(mozIStorageConnection* aDBConn) { RefPtr function = new NoteSyncChangeFunction(); - nsresult rv = aDBConn->CreateFunction(NS_LITERAL_CSTRING("note_sync_change"), - 0, function); + nsresult rv = aDBConn->CreateFunction("note_sync_change"_ns, 0, function); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; diff --git a/toolkit/components/places/Shutdown.cpp b/toolkit/components/places/Shutdown.cpp index 314f3c6d1a73..f07b6e101820 100644 --- a/toolkit/components/places/Shutdown.cpp +++ b/toolkit/components/places/Shutdown.cpp @@ -58,7 +58,7 @@ PlacesShutdownBlocker::GetState(nsIPropertyBag** _state) { nsresult rv = progress->SetAsUint8(mState); if (NS_WARN_IF(NS_FAILED(rv))) return rv; rv = static_cast(*_state)->SetPropertyAsInterface( - NS_LITERAL_STRING("progress"), progress); + u"progress"_ns, progress); if (NS_WARN_IF(NS_FAILED(rv))) return rv; // Put `mBarrier`'s state in field `barrier`, if possible @@ -75,7 +75,7 @@ PlacesShutdownBlocker::GetState(nsIPropertyBag** _state) { rv = barrier->SetAsInterface(NS_GET_IID(nsIPropertyBag), barrierState); if (NS_WARN_IF(NS_FAILED(rv))) return rv; rv = static_cast(*_state)->SetPropertyAsInterface( - NS_LITERAL_STRING("Barrier"), barrier); + u"Barrier"_ns, barrier); if (NS_WARN_IF(NS_FAILED(rv))) return rv; return NS_OK; @@ -121,7 +121,7 @@ NS_IMPL_ISUPPORTS(PlacesShutdownBlocker, nsIAsyncShutdownBlocker, //////////////////////////////////////////////////////////////////////////////// ClientsShutdownBlocker::ClientsShutdownBlocker() - : PlacesShutdownBlocker(NS_LITERAL_STRING("Places Clients shutdown")) { + : PlacesShutdownBlocker(u"Places Clients shutdown"_ns) { // Do nothing. } @@ -145,7 +145,7 @@ ClientsShutdownBlocker::Done() { //////////////////////////////////////////////////////////////////////////////// ConnectionShutdownBlocker::ConnectionShutdownBlocker(Database* aDatabase) - : PlacesShutdownBlocker(NS_LITERAL_STRING("Places Connection shutdown")), + : PlacesShutdownBlocker(u"Places Connection shutdown"_ns), mDatabase(aDatabase) { // Do nothing. } diff --git a/toolkit/components/places/nsAnnoProtocolHandler.cpp b/toolkit/components/places/nsAnnoProtocolHandler.cpp index e765accfe6ae..26a5500b8008 100644 --- a/toolkit/components/places/nsAnnoProtocolHandler.cpp +++ b/toolkit/components/places/nsAnnoProtocolHandler.cpp @@ -45,15 +45,15 @@ static nsresult GetDefaultIcon(nsIChannel* aOriginalChannel, nsIChannel** aChannel) { nsCOMPtr defaultIconURI; nsresult rv = NS_NewURI(getter_AddRefs(defaultIconURI), - NS_LITERAL_CSTRING(FAVICON_DEFAULT_URL)); + nsLiteralCString(FAVICON_DEFAULT_URL)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr loadInfo = aOriginalChannel->LoadInfo(); rv = NS_NewChannelInternal(aChannel, defaultIconURI, loadInfo); NS_ENSURE_SUCCESS(rv, rv); Unused << (*aChannel)->SetContentType( - NS_LITERAL_CSTRING(FAVICON_DEFAULT_MIMETYPE)); + nsLiteralCString(FAVICON_DEFAULT_MIMETYPE)); Unused << aOriginalChannel->SetContentType( - NS_LITERAL_CSTRING(FAVICON_DEFAULT_MIMETYPE)); + nsLiteralCString(FAVICON_DEFAULT_MIMETYPE)); return NS_OK; } @@ -103,9 +103,9 @@ class faviconAsyncLoader : public AsyncStatementCallback { // Eventually override the default mimeType for svg. if (width == UINT16_MAX) { - rv = mChannel->SetContentType(NS_LITERAL_CSTRING(SVG_MIME_TYPE)); + rv = mChannel->SetContentType(nsLiteralCString(SVG_MIME_TYPE)); } else { - rv = mChannel->SetContentType(NS_LITERAL_CSTRING(PNG_MIME_TYPE)); + rv = mChannel->SetContentType(nsLiteralCString(PNG_MIME_TYPE)); } NS_ENSURE_SUCCESS(rv, rv); diff --git a/toolkit/components/places/nsAnnotationService.cpp b/toolkit/components/places/nsAnnotationService.cpp index 4e3af7ad3d19..0f336538799c 100644 --- a/toolkit/components/places/nsAnnotationService.cpp +++ b/toolkit/components/places/nsAnnotationService.cpp @@ -72,7 +72,7 @@ nsresult nsAnnotationService::SetAnnotationStringInternal( mozStorageStatementScoper scoper(statement); - rv = statement->BindStringByName(NS_LITERAL_CSTRING("content"), aValue); + rv = statement->BindStringByName("content"_ns, aValue); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -177,7 +177,7 @@ nsresult nsAnnotationService::SetAnnotationInt32Internal( mozStorageStatementScoper scoper(statement); - rv = statement->BindInt32ByName(NS_LITERAL_CSTRING("content"), aValue); + rv = statement->BindInt32ByName("content"_ns, aValue); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -201,7 +201,7 @@ nsresult nsAnnotationService::SetAnnotationInt64Internal( mozStorageStatementScoper scoper(statement); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("content"), aValue); + rv = statement->BindInt64ByName("content"_ns, aValue); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -225,7 +225,7 @@ nsresult nsAnnotationService::SetAnnotationDoubleInternal( mozStorageStatementScoper scoper(statement); - rv = statement->BindDoubleByName(NS_LITERAL_CSTRING("content"), aValue); + rv = statement->BindDoubleByName("content"_ns, aValue); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -299,10 +299,10 @@ nsresult nsAnnotationService::RemoveAnnotationInternal( mozStorageStatementScoper scoper(statement); nsresult rv; - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + rv = statement->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); - rv = statement->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), aName); + rv = statement->BindUTF8StringByName("anno_name"_ns, aName); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -341,8 +341,7 @@ nsresult nsAnnotationService::RemoveItemAnnotations(int64_t aItemId) { NS_ENSURE_STATE(statement); mozStorageStatementScoper scoper(statement); - nsresult rv = - statement->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + nsresult rv = statement->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -368,10 +367,9 @@ nsAnnotationService::ItemHasAnnotation(int64_t aItemId, const nsACString& aName, NS_ENSURE_STATE(stmt); mozStorageStatementScoper checkAnnoScoper(stmt); - nsresult rv = - stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), aName); + nsresult rv = stmt->BindUTF8StringByName("anno_name"_ns, aName); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + rv = stmt->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); bool hasResult; @@ -414,10 +412,10 @@ nsresult nsAnnotationService::StartGetAnnotation( mozStorageStatementScoper getAnnoScoper(aStatement); nsresult rv; - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + rv = aStatement->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), aName); + rv = aStatement->BindUTF8StringByName("anno_name"_ns, aName); NS_ENSURE_SUCCESS(rv, rv); bool hasResult = false; @@ -453,8 +451,7 @@ nsresult nsAnnotationService::StartSetAnnotation( NS_ENSURE_STATE(addNameStmt); mozStorageStatementScoper scoper(addNameStmt); - nsresult rv = - addNameStmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), aName); + nsresult rv = addNameStmt->BindUTF8StringByName("anno_name"_ns, aName); NS_ENSURE_SUCCESS(rv, rv); rv = addNameStmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -479,9 +476,9 @@ nsresult nsAnnotationService::StartSetAnnotation( NS_ENSURE_STATE(stmt); mozStorageStatementScoper checkAnnoScoper(stmt); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("anno_name"), aName); + rv = stmt->BindUTF8StringByName("anno_name"_ns, aName); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + rv = stmt->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); bool hasResult; @@ -522,33 +519,29 @@ nsresult nsAnnotationService::StartSetAnnotation( // Don't replace existing annotations. if (oldAnnoId > 0) { - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("id"), oldAnnoId); + rv = aStatement->BindInt64ByName("id"_ns, oldAnnoId); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("date_added"), - oldAnnoDate); + rv = aStatement->BindInt64ByName("date_added"_ns, oldAnnoDate); NS_ENSURE_SUCCESS(rv, rv); } else { - rv = aStatement->BindNullByName(NS_LITERAL_CSTRING("id")); + rv = aStatement->BindNullByName("id"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("date_added"), - RoundedPRNow()); + rv = aStatement->BindInt64ByName("date_added"_ns, RoundedPRNow()); NS_ENSURE_SUCCESS(rv, rv); } - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("fk"), fkId); + rv = aStatement->BindInt64ByName("fk"_ns, fkId); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("name_id"), nameID); + rv = aStatement->BindInt64ByName("name_id"_ns, nameID); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("flags"), aFlags); + rv = aStatement->BindInt32ByName("flags"_ns, aFlags); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("expiration"), - aExpiration); + rv = aStatement->BindInt32ByName("expiration"_ns, aExpiration); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt32ByName(NS_LITERAL_CSTRING("type"), aType); + rv = aStatement->BindInt32ByName("type"_ns, aType); NS_ENSURE_SUCCESS(rv, rv); - rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("last_modified"), - RoundedPRNow()); + rv = aStatement->BindInt64ByName("last_modified"_ns, RoundedPRNow()); NS_ENSURE_SUCCESS(rv, rv); // On success, leave the statement open, the caller will set the value diff --git a/toolkit/components/places/nsFaviconService.cpp b/toolkit/components/places/nsFaviconService.cpp index 6618436965d1..75dd717b6c73 100644 --- a/toolkit/components/places/nsFaviconService.cpp +++ b/toolkit/components/places/nsFaviconService.cpp @@ -238,7 +238,7 @@ nsFaviconService::GetDefaultFavicon(nsIURI** _retval) { // not found, use default if (!mDefaultIcon) { nsresult rv = NS_NewURI(getter_AddRefs(mDefaultIcon), - NS_LITERAL_CSTRING(FAVICON_DEFAULT_URL)); + nsLiteralCString(FAVICON_DEFAULT_URL)); NS_ENSURE_SUCCESS(rv, rv); } @@ -249,7 +249,7 @@ nsFaviconService::GetDefaultFavicon(nsIURI** _retval) { NS_IMETHODIMP nsFaviconService::GetDefaultFaviconMimeType(nsACString& _retval) { - _retval = NS_LITERAL_CSTRING(FAVICON_DEFAULT_MIMETYPE); + _retval = nsLiteralCString(FAVICON_DEFAULT_MIMETYPE); return NS_OK; } @@ -303,11 +303,11 @@ nsFaviconService::SetAndFetchFaviconForPage( if (!loadingPrincipal) { // Let's default to the nullPrincipal if no loadingPrincipal is provided. AutoTArray params = { - NS_LITERAL_STRING("nsFaviconService::setAndFetchFaviconForPage()"), - NS_LITERAL_STRING("nsFaviconService::setAndFetchFaviconForPage(..., " - "[optional aLoadingPrincipal])")}; + u"nsFaviconService::setAndFetchFaviconForPage()"_ns, + u"nsFaviconService::setAndFetchFaviconForPage(..., " + "[optional aLoadingPrincipal])"_ns}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security by Default"), + nsIScriptError::warningFlag, "Security by Default"_ns, nullptr, // aDocument nsContentUtils::eNECKO_PROPERTIES, "APIDeprecationWarning", params); loadingPrincipal = NullPrincipal::CreateWithoutOriginAttributes(); @@ -323,7 +323,7 @@ nsFaviconService::SetAndFetchFaviconForPage( NS_ENSURE_SUCCESS(rv, rv); // URIs can arguably lack a host. Unused << aPageURI->GetHost(page.host); - if (StringBeginsWith(page.host, NS_LITERAL_CSTRING("www."))) { + if (StringBeginsWith(page.host, "www."_ns)) { page.host.Cut(0, 4); } bool canAddToHistory; @@ -346,7 +346,7 @@ nsFaviconService::SetAndFetchFaviconForPage( NS_ENSURE_SUCCESS(rv, rv); // URIs can arguably lack a host. Unused << aFaviconURI->GetHost(icon.host); - if (StringBeginsWith(icon.host, NS_LITERAL_CSTRING("www."))) { + if (StringBeginsWith(icon.host, "www."_ns)) { icon.host.Cut(0, 4); } } @@ -427,7 +427,7 @@ nsFaviconService::ReplaceFaviconData(nsIURI* aFaviconURI, NS_ENSURE_SUCCESS(rv, rv); // URIs can arguably lack a host. Unused << aFaviconURI->GetHost(iconData->host); - if (StringBeginsWith(iconData->host, NS_LITERAL_CSTRING("www."))) { + if (StringBeginsWith(iconData->host, "www."_ns)) { iconData->host.Cut(0, 4); } @@ -497,11 +497,11 @@ nsFaviconService::ReplaceFaviconDataFromDataURL( if (!loadingPrincipal) { // Let's default to the nullPrincipal if no loadingPrincipal is provided. AutoTArray params = { - NS_LITERAL_STRING("nsFaviconService::ReplaceFaviconDataFromDataURL()"), - NS_LITERAL_STRING("nsFaviconService::ReplaceFaviconDataFromDataURL(...," - " [optional aLoadingPrincipal])")}; + u"nsFaviconService::ReplaceFaviconDataFromDataURL()"_ns, + u"nsFaviconService::ReplaceFaviconDataFromDataURL(...," + " [optional aLoadingPrincipal])"_ns}; nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security by Default"), + nsIScriptError::warningFlag, "Security by Default"_ns, nullptr, // aDocument nsContentUtils::eNECKO_PROPERTIES, "APIDeprecationWarning", params); @@ -668,7 +668,7 @@ nsresult nsFaviconService::GetFaviconLinkForIconString(const nsCString& aSpec, return GetDefaultFavicon(aOutput); } - if (StringBeginsWith(aSpec, NS_LITERAL_CSTRING("chrome:"))) { + if (StringBeginsWith(aSpec, "chrome:"_ns)) { // pass through for chrome URLs, since they can be referenced without // this service return NS_NewURI(aOutput, aSpec); @@ -722,7 +722,7 @@ nsresult nsFaviconService::OptimizeIconSizes(IconData& aIcon) { for (const auto& frameInfo : framesInfo) { IconPayload newPayload; - newPayload.mimeType = NS_LITERAL_CSTRING(PNG_MIME_TYPE); + newPayload.mimeType = nsLiteralCString(PNG_MIME_TYPE); newPayload.width = frameInfo.width; for (uint16_t size : gFaviconSizes) { // The icon could be smaller than 16, that is our minimum. @@ -782,7 +782,7 @@ nsresult nsFaviconService::GetFaviconDataAsync( "ORDER BY width DESC"); NS_ENSURE_STATE(stmt); - nsresult rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("url"), aFaviconURI); + nsresult rv = URIBinder::Bind(stmt, "url"_ns, aFaviconURI); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr pendingStatement; diff --git a/toolkit/components/places/nsNavBookmarks.cpp b/toolkit/components/places/nsNavBookmarks.cpp index 528cd7072f4e..37a868634716 100644 --- a/toolkit/components/places/nsNavBookmarks.cpp +++ b/toolkit/components/places/nsNavBookmarks.cpp @@ -80,8 +80,7 @@ class AsyncGetBookmarksForURI : public AsyncStatementCallback { "hash(:page_url) AND url = :page_url) " "ORDER BY b.lastModified DESC, b.id DESC "); if (stmt) { - (void)URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), - mData.bookmark.url); + (void)URIBinder::Bind(stmt, "page_url"_ns, mData.bookmark.url); nsCOMPtr pendingStmt; (void)stmt->ExecuteAsync(this, getter_AddRefs(pendingStmt)); } @@ -219,13 +218,13 @@ nsresult nsNavBookmarks::AdjustIndices(int64_t aFolderId, int32_t aStartIndex, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("delta"), aDelta); + nsresult rv = stmt->BindInt32ByName("delta"_ns, aDelta); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + rv = stmt->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("from_index"), aStartIndex); + rv = stmt->BindInt32ByName("from_index"_ns, aStartIndex); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("to_index"), aEndIndex); + rv = stmt->BindInt32ByName("to_index"_ns, aEndIndex); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -249,14 +248,13 @@ nsresult nsNavBookmarks::AdjustSeparatorsSyncCounter(int64_t aFolderId, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - stmt->BindInt64ByName(NS_LITERAL_CSTRING("delta"), aSyncChangeDelta); + nsresult rv = stmt->BindInt64ByName("delta"_ns, aSyncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + rv = stmt->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("start_index"), aStartIndex); + rv = stmt->BindInt32ByName("start_index"_ns, aStartIndex); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("item_type"), TYPE_SEPARATOR); + rv = stmt->BindInt32ByName("item_type"_ns, TYPE_SEPARATOR); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -325,38 +323,37 @@ nsresult nsNavBookmarks::InsertBookmarkInDB( nsresult rv; if (*_itemId != -1) - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), *_itemId); + rv = stmt->BindInt64ByName("item_id"_ns, *_itemId); else - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("item_id")); + rv = stmt->BindNullByName("item_id"_ns); NS_ENSURE_SUCCESS(rv, rv); if (aPlaceId != -1) - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), aPlaceId); + rv = stmt->BindInt64ByName("page_id"_ns, aPlaceId); else - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("page_id")); + rv = stmt->BindNullByName("page_id"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("item_type"), aItemType); + rv = stmt->BindInt32ByName("item_type"_ns, aItemType); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aParentId); + rv = stmt->BindInt64ByName("parent"_ns, aParentId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("item_index"), aIndex); + rv = stmt->BindInt32ByName("item_index"_ns, aIndex); NS_ENSURE_SUCCESS(rv, rv); if (aTitle.IsEmpty()) - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("item_title")); + rv = stmt->BindNullByName("item_title"_ns); else - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_title"), aTitle); + rv = stmt->BindUTF8StringByName("item_title"_ns, aTitle); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("date_added"), aDateAdded); + rv = stmt->BindInt64ByName("date_added"_ns, aDateAdded); NS_ENSURE_SUCCESS(rv, rv); if (aLastModified) { - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("last_modified"), - aLastModified); + rv = stmt->BindInt64ByName("last_modified"_ns, aLastModified); } else { - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("last_modified"), aDateAdded); + rv = stmt->BindInt64ByName("last_modified"_ns, aDateAdded); } NS_ENSURE_SUCCESS(rv, rv); @@ -365,24 +362,23 @@ nsresult nsNavBookmarks::InsertBookmarkInDB( bool hasExistingGuid = _guid.Length() == 12; if (hasExistingGuid) { MOZ_ASSERT(IsValidGUID(_guid)); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_guid"), _guid); + rv = stmt->BindUTF8StringByName("item_guid"_ns, _guid); NS_ENSURE_SUCCESS(rv, rv); } else { nsAutoCString guid; rv = GenerateGUID(guid); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_guid"), guid); + rv = stmt->BindUTF8StringByName("item_guid"_ns, guid); NS_ENSURE_SUCCESS(rv, rv); _guid.Assign(guid); } int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("change_counter"), - syncChangeDelta); + rv = stmt->BindInt64ByName("change_counter"_ns, syncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); uint16_t syncStatus = DetermineInitialSyncStatus(aSource); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("sync_status"), syncStatus); + rv = stmt->BindInt32ByName("sync_status"_ns, syncStatus); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -542,9 +538,9 @@ nsNavBookmarks::InsertBookmark(int64_t aFolder, nsIURI* aURI, int32_t aIndex, NOTIFY_BOOKMARKS_OBSERVERS( mCanNotify, mObservers, DontSkip, - OnItemChanged(bookmarks[i].id, NS_LITERAL_CSTRING("tags"), false, - EmptyCString(), bookmarks[i].lastModified, - TYPE_BOOKMARK, bookmarks[i].parentId, bookmarks[i].guid, + OnItemChanged(bookmarks[i].id, "tags"_ns, false, EmptyCString(), + bookmarks[i].lastModified, TYPE_BOOKMARK, + bookmarks[i].parentId, bookmarks[i].guid, bookmarks[i].parentGuid, EmptyCString(), aSource)); } } @@ -585,7 +581,7 @@ nsNavBookmarks::RemoveItem(int64_t aItemId, uint16_t aSource) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), bookmark.id); + rv = stmt->BindInt64ByName("item_id"_ns, bookmark.id); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -671,9 +667,9 @@ nsNavBookmarks::RemoveItem(int64_t aItemId, uint16_t aSource) { for (uint32_t i = 0; i < bookmarks.Length(); ++i) { NOTIFY_BOOKMARKS_OBSERVERS( mCanNotify, mObservers, DontSkip, - OnItemChanged(bookmarks[i].id, NS_LITERAL_CSTRING("tags"), false, - EmptyCString(), bookmarks[i].lastModified, - TYPE_BOOKMARK, bookmarks[i].parentId, bookmarks[i].guid, + OnItemChanged(bookmarks[i].id, "tags"_ns, false, EmptyCString(), + bookmarks[i].lastModified, TYPE_BOOKMARK, + bookmarks[i].parentId, bookmarks[i].guid, bookmarks[i].parentGuid, EmptyCString(), aSource)); } } @@ -772,7 +768,7 @@ nsresult nsNavBookmarks::GetDescendantChildren( NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + rv = stmt->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); bool hasMore; @@ -861,14 +857,13 @@ nsresult nsNavBookmarks::RemoveFolderChildren(int64_t aFolderId, mozStorageTransaction transaction(mDB->MainConn(), false); nsCOMPtr deleteStatement = - mDB->GetStatement(NS_LITERAL_CSTRING("DELETE FROM moz_bookmarks " - "WHERE parent IN (:parent") + - foldersToRemove + NS_LITERAL_CSTRING(")")); + mDB->GetStatement(nsLiteralCString("DELETE FROM moz_bookmarks " + "WHERE parent IN (:parent") + + foldersToRemove + ")"_ns); NS_ENSURE_STATE(deleteStatement); mozStorageStatementScoper deleteStatementScoper(deleteStatement); - rv = - deleteStatement->BindInt64ByName(NS_LITERAL_CSTRING("parent"), folder.id); + rv = deleteStatement->BindInt64ByName("parent"_ns, folder.id); NS_ENSURE_SUCCESS(rv, rv); rv = deleteStatement->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -879,11 +874,11 @@ nsresult nsNavBookmarks::RemoveFolderChildren(int64_t aFolderId, return NS_ERROR_UNEXPECTED; } rv = conn->ExecuteSimpleSQL( - NS_LITERAL_CSTRING("DELETE FROM moz_items_annos " - "WHERE id IN (" - "SELECT a.id from moz_items_annos a " - "LEFT JOIN moz_bookmarks b ON a.item_id = b.id " - "WHERE b.id ISNULL)")); + nsLiteralCString("DELETE FROM moz_items_annos " + "WHERE id IN (" + "SELECT a.id from moz_items_annos a " + "LEFT JOIN moz_bookmarks b ON a.item_id = b.id " + "WHERE b.id ISNULL)")); NS_ENSURE_SUCCESS(rv, rv); // Set the lastModified date. @@ -969,11 +964,10 @@ nsresult nsNavBookmarks::RemoveFolderChildren(int64_t aFolderId, for (uint32_t i = 0; i < bookmarks.Length(); ++i) { NOTIFY_BOOKMARKS_OBSERVERS( mCanNotify, mObservers, DontSkip, - OnItemChanged(bookmarks[i].id, NS_LITERAL_CSTRING("tags"), false, - EmptyCString(), bookmarks[i].lastModified, - TYPE_BOOKMARK, bookmarks[i].parentId, - bookmarks[i].guid, bookmarks[i].parentGuid, - EmptyCString(), aSource)); + OnItemChanged(bookmarks[i].id, "tags"_ns, false, EmptyCString(), + bookmarks[i].lastModified, TYPE_BOOKMARK, + bookmarks[i].parentId, bookmarks[i].guid, + bookmarks[i].parentGuid, EmptyCString(), aSource)); } } } @@ -995,7 +989,7 @@ nsresult nsNavBookmarks::FetchItemInfo(int64_t aItemId, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + nsresult rv = stmt->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); bool hasResult; @@ -1061,8 +1055,7 @@ nsresult nsNavBookmarks::FetchItemInfo(const nsCString& aGUID, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("item_guid"), aGUID); + nsresult rv = stmt->BindUTF8StringByName("item_guid"_ns, aGUID); NS_ENSURE_SUCCESS(rv, rv); _bookmark.guid = aGUID; @@ -1128,11 +1121,11 @@ nsresult nsNavBookmarks::SetItemDateInternal(enum BookmarkDate aDateType, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("date"), aValue); + nsresult rv = stmt->BindInt64ByName("date"_ns, aValue); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aItemId); + rv = stmt->BindInt64ByName("item_id"_ns, aItemId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("delta"), aSyncChangeDelta); + rv = stmt->BindInt64ByName("delta"_ns, aSyncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1185,7 +1178,7 @@ nsNavBookmarks::SetItemLastModified(int64_t aItemId, PRTime aLastModified, NOTIFY_BOOKMARKS_OBSERVERS( mCanNotify, mObservers, SKIP_TAGS(isTagging || bookmark.parentId == tagsRootId), - OnItemChanged(bookmark.id, NS_LITERAL_CSTRING("lastModified"), false, + OnItemChanged(bookmark.id, "lastModified"_ns, false, nsPrintfCString("%" PRId64, bookmark.lastModified), bookmark.lastModified, bookmark.type, bookmark.parentId, bookmark.guid, bookmark.parentGuid, EmptyCString(), @@ -1223,13 +1216,12 @@ nsresult nsNavBookmarks::AddSyncChangesForBookmarksWithURI( NS_ENSURE_STATE(statement); mozStorageStatementScoper scoper(statement); - nsresult rv = - statement->BindInt64ByName(NS_LITERAL_CSTRING("delta"), aSyncChangeDelta); + nsresult rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("type"), + rv = statement->BindInt64ByName("type"_ns, nsINavBookmarksService::TYPE_BOOKMARK); NS_ENSURE_SUCCESS(rv, rv); - rv = URIBinder::Bind(statement, NS_LITERAL_CSTRING("url"), aURI); + rv = URIBinder::Bind(statement, "url"_ns, aURI); NS_ENSURE_SUCCESS(rv, rv); return statement->Execute(); @@ -1249,13 +1241,12 @@ nsresult nsNavBookmarks::AddSyncChangesForBookmarksInFolder( NS_ENSURE_STATE(statement); mozStorageStatementScoper scoper(statement); - nsresult rv = - statement->BindInt64ByName(NS_LITERAL_CSTRING("delta"), aSyncChangeDelta); + nsresult rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("type"), + rv = statement->BindInt64ByName("type"_ns, nsINavBookmarksService::TYPE_BOOKMARK); NS_ENSURE_SUCCESS(rv, rv); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + rv = statement->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -1274,11 +1265,9 @@ nsresult nsNavBookmarks::InsertTombstone(const BookmarkData& aBookmark) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aBookmark.guid); + nsresult rv = stmt->BindUTF8StringByName("guid"_ns, aBookmark.guid); NS_ENSURE_SUCCESS(rv, rv); - rv = - stmt->BindInt64ByName(NS_LITERAL_CSTRING("date_removed"), RoundedPRNow()); + rv = stmt->BindInt64ByName("date_removed"_ns, RoundedPRNow()); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -1318,10 +1307,10 @@ nsresult nsNavBookmarks::InsertTombstones( "Expected one binding param per column for each tombstone"); #endif - nsCOMPtr stmt = mDB->GetStatement( - NS_LITERAL_CSTRING("INSERT INTO moz_bookmarks_deleted " - "(guid, dateRemoved) ") + - tombstonesToInsert); + nsCOMPtr stmt = + mDB->GetStatement(nsLiteralCString("INSERT INTO moz_bookmarks_deleted " + "(guid, dateRemoved) ") + + tombstonesToInsert); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); @@ -1347,7 +1336,7 @@ nsresult nsNavBookmarks::RemoveTombstone(const nsACString& aGUID) { NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aGUID); + nsresult rv = stmt->BindUTF8StringByName("guid"_ns, aGUID); NS_ENSURE_SUCCESS(rv, rv); return stmt->Execute(); @@ -1390,7 +1379,7 @@ nsNavBookmarks::SetItemTitle(int64_t aItemId, const nsACString& aTitle, NOTIFY_BOOKMARKS_OBSERVERS( mCanNotify, mObservers, SKIP_TAGS(isChangingTagFolder), - OnItemChanged(bookmark.id, NS_LITERAL_CSTRING("title"), false, title, + OnItemChanged(bookmark.id, "title"_ns, false, title, bookmark.lastModified, bookmark.type, bookmark.parentId, bookmark.guid, bookmark.parentGuid, EmptyCString(), aSource)); @@ -1410,20 +1399,17 @@ nsresult nsNavBookmarks::SetItemTitleInternal(BookmarkData& aBookmark, nsresult rv; if (aTitle.IsEmpty()) { - rv = statement->BindNullByName(NS_LITERAL_CSTRING("item_title")); + rv = statement->BindNullByName("item_title"_ns); } else { - rv = statement->BindUTF8StringByName(NS_LITERAL_CSTRING("item_title"), - aTitle); + rv = statement->BindUTF8StringByName("item_title"_ns, aTitle); } NS_ENSURE_SUCCESS(rv, rv); aBookmark.lastModified = RoundToMilliseconds(RoundedPRNow()); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("date"), - aBookmark.lastModified); + rv = statement->BindInt64ByName("date"_ns, aBookmark.lastModified); NS_ENSURE_SUCCESS(rv, rv); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aBookmark.id); + rv = statement->BindInt64ByName("item_id"_ns, aBookmark.id); NS_ENSURE_SUCCESS(rv, rv); - rv = - statement->BindInt64ByName(NS_LITERAL_CSTRING("delta"), aSyncChangeDelta); + rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta); NS_ENSURE_SUCCESS(rv, rv); rv = statement->Execute(); @@ -1508,12 +1494,11 @@ nsresult nsNavBookmarks::QueryFolderChildren( NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + nsresult rv = stmt->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("folder"), TYPE_FOLDER); + rv = stmt->BindInt32ByName("folder"_ns, TYPE_FOLDER); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("excludeItems"), - aOptions->ExcludeItems()); + rv = stmt->BindInt32ByName("excludeItems"_ns, aOptions->ExcludeItems()); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr row = do_QueryInterface(stmt, &rv); @@ -1635,13 +1620,12 @@ nsresult nsNavBookmarks::QueryFolderChildrenAsync( "ORDER BY b.position ASC"); NS_ENSURE_STATE(stmt); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), - aNode->mTargetFolderItemId); + nsresult rv = stmt->BindInt64ByName("parent"_ns, aNode->mTargetFolderItemId); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("folder"), TYPE_FOLDER); + rv = stmt->BindInt32ByName("folder"_ns, TYPE_FOLDER); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("excludeItems"), - aNode->mOptions->ExcludeItems()); + rv = + stmt->BindInt32ByName("excludeItems"_ns, aNode->mOptions->ExcludeItems()); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr pendingStmt; @@ -1670,7 +1654,7 @@ nsresult nsNavBookmarks::FetchFolderInfo(int64_t aFolderId, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("parent"), aFolderId); + nsresult rv = stmt->BindInt64ByName("parent"_ns, aFolderId); NS_ENSURE_SUCCESS(rv, rv); bool hasResult; @@ -1732,7 +1716,7 @@ nsresult nsNavBookmarks::GetBookmarksForURI( NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), aURI); + nsresult rv = URIBinder::Bind(stmt, "page_url"_ns, aURI); NS_ENSURE_SUCCESS(rv, rv); int64_t tagsRootId = TagsRootId(); @@ -1937,7 +1921,7 @@ nsNavBookmarks::OnPageChanged(nsIURI* aURI, uint32_t aChangedAttribute, ItemChangeData changeData; rv = aURI->GetSpec(changeData.bookmark.url); NS_ENSURE_SUCCESS(rv, rv); - changeData.property = NS_LITERAL_CSTRING("favicon"); + changeData.property = "favicon"_ns; changeData.isAnnotation = false; changeData.newValue = NS_ConvertUTF16toUTF8(aNewValue); changeData.bookmark.lastModified = 0; @@ -1985,7 +1969,7 @@ nsNavBookmarks::OnDeleteVisits(nsIURI* aURI, bool aPartialRemoval, ItemChangeData changeData; nsresult rv = aURI->GetSpec(changeData.bookmark.url); NS_ENSURE_SUCCESS(rv, rv); - changeData.property = NS_LITERAL_CSTRING("cleartime"); + changeData.property = "cleartime"_ns; changeData.isAnnotation = false; changeData.bookmark.lastModified = 0; changeData.bookmark.type = TYPE_BOOKMARK; diff --git a/toolkit/components/places/nsNavHistory.cpp b/toolkit/components/places/nsNavHistory.cpp index d51317108270..8cb68ed7d541 100644 --- a/toolkit/components/places/nsNavHistory.cpp +++ b/toolkit/components/places/nsNavHistory.cpp @@ -118,7 +118,7 @@ using namespace mozilla::places; #define RENEW_CACHED_NOW_TIMEOUT ((int32_t)3 * PR_MSEC_PER_SEC) // character-set annotation -#define CHARSET_ANNO NS_LITERAL_CSTRING("URIProperties/characterSet") +#define CHARSET_ANNO "URIProperties/characterSet"_ns // These macros are used when splitting history by date. // These are the day containers and catch-all final container. @@ -198,16 +198,16 @@ void GetTagsSqlFragment(int64_t aTagsFolder, const nsACString& aRelation, else { // This subquery DOES NOT order tags for performance reasons. _sqlFragment.Assign( - NS_LITERAL_CSTRING("(SELECT GROUP_CONCAT(t_t.title, ',') " - "FROM moz_bookmarks b_t " - "JOIN moz_bookmarks t_t ON t_t.id = +b_t.parent " - "WHERE b_t.fk = ") + + nsLiteralCString("(SELECT GROUP_CONCAT(t_t.title, ',') " + "FROM moz_bookmarks b_t " + "JOIN moz_bookmarks t_t ON t_t.id = +b_t.parent " + "WHERE b_t.fk = ") + aRelation + - NS_LITERAL_CSTRING(" " - "AND t_t.parent = ") + + nsLiteralCString(" " + "AND t_t.parent = ") + nsPrintfCString("%" PRId64, aTagsFolder) + - NS_LITERAL_CSTRING(" " - ")")); + nsLiteralCString(" " + ")")); } _sqlFragment.AppendLiteral(" AS tags "); @@ -301,7 +301,7 @@ class FixAndDecayFrecencyRunnable final : public Runnable { "WHERE frecency > 0"); NS_ENSURE_STATE(decayFrecency); nsresult rv = decayFrecency->BindDoubleByName( - NS_LITERAL_CSTRING("decay_rate"), static_cast(mDecayRate)); + "decay_rate"_ns, static_cast(mDecayRate)); NS_ENSURE_SUCCESS(rv, rv); rv = decayFrecency->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -311,7 +311,7 @@ class FixAndDecayFrecencyRunnable final : public Runnable { nsCOMPtr decayAdaptive = mDB->GetStatement( "UPDATE moz_inputhistory SET use_count = use_count * :decay_rate"); NS_ENSURE_STATE(decayAdaptive); - rv = decayAdaptive->BindDoubleByName(NS_LITERAL_CSTRING("decay_rate"), + rv = decayAdaptive->BindDoubleByName("decay_rate"_ns, static_cast(mDecayRate)); NS_ENSURE_SUCCESS(rv, rv); rv = decayAdaptive->Execute(); @@ -322,9 +322,8 @@ class FixAndDecayFrecencyRunnable final : public Runnable { "DELETE FROM moz_inputhistory WHERE use_count < :use_count"); NS_ENSURE_STATE(deleteAdaptive); rv = deleteAdaptive->BindDoubleByName( - NS_LITERAL_CSTRING("use_count"), - std::pow(static_cast(mDecayRate), - ADAPTIVE_HISTORY_EXPIRE_DAYS)); + "use_count"_ns, std::pow(static_cast(mDecayRate), + ADAPTIVE_HISTORY_EXPIRE_DAYS)); NS_ENSURE_SUCCESS(rv, rv); rv = deleteAdaptive->Execute(); NS_ENSURE_SUCCESS(rv, rv); @@ -482,7 +481,7 @@ nsresult nsNavHistory::GetIdForPage(nsIURI* aURI, int64_t* _pageId, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), aURI); + nsresult rv = URIBinder::Bind(stmt, "page_url"_ns, aURI); NS_ENSURE_SUCCESS(rv, rv); bool hasEntry = false; @@ -518,29 +517,28 @@ nsresult nsNavHistory::GetOrCreateIdForPage(nsIURI* aURI, int64_t* _pageId, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), aURI); + rv = URIBinder::Bind(stmt, "page_url"_ns, aURI); NS_ENSURE_SUCCESS(rv, rv); // host (reversed with trailing period) nsAutoString revHost; rv = GetReversedHostname(aURI, revHost); // Not all URI types have hostnames, so this is optional. if (NS_SUCCEEDED(rv)) { - rv = stmt->BindStringByName(NS_LITERAL_CSTRING("rev_host"), revHost); + rv = stmt->BindStringByName("rev_host"_ns, revHost); } else { - rv = stmt->BindNullByName(NS_LITERAL_CSTRING("rev_host")); + rv = stmt->BindNullByName("rev_host"_ns); } NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("hidden"), 1); + rv = stmt->BindInt32ByName("hidden"_ns, 1); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString spec; rv = aURI->GetSpec(spec); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("frecency"), - IsQueryURI(spec) ? 0 : -1); + rv = stmt->BindInt32ByName("frecency"_ns, IsQueryURI(spec) ? 0 : -1); NS_ENSURE_SUCCESS(rv, rv); rv = GenerateGUID(_GUID); NS_ENSURE_SUCCESS(rv, rv); - rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), _GUID); + rv = stmt->BindUTF8StringByName("guid"_ns, _GUID); NS_ENSURE_SUCCESS(rv, rv); rv = stmt->Execute(); @@ -680,7 +678,7 @@ nsresult nsNavHistory::RecalculateOriginFrecencyStatsInternal() { nsCOMPtr conn(mDB->MainConn()); NS_ENSURE_STATE(conn); - nsresult rv = conn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( + nsresult rv = conn->ExecuteSimpleSQL(nsLiteralCString( "INSERT OR REPLACE INTO moz_meta(key, value) VALUES " "( " "'" MOZ_META_KEY_ORIGIN_FRECENCY_COUNT @@ -1231,15 +1229,15 @@ nsresult PlacesSQLQueryBuilder::SelectAsURI() { switch (mQueryType) { case nsINavHistoryQueryOptions::QUERY_TYPE_HISTORY: - GetTagsSqlFragment(history->GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), - mHasSearchTerms, tagsSqlFragment); + GetTagsSqlFragment(history->GetTagsFolder(), "h.id"_ns, mHasSearchTerms, + tagsSqlFragment); - mQueryString = NS_LITERAL_CSTRING( + mQueryString = nsLiteralCString( "SELECT h.id, h.url, h.title AS page_title, " "h.rev_host, h.visit_count, " "h.last_visit_date, null, null, null, null, null, ") + tagsSqlFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( ", h.frecency, h.hidden, h.guid, " "null, null, null " "FROM moz_places h " @@ -1252,15 +1250,15 @@ nsresult PlacesSQLQueryBuilder::SelectAsURI() { case nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS: - GetTagsSqlFragment(history->GetTagsFolder(), NS_LITERAL_CSTRING("b.fk"), - mHasSearchTerms, tagsSqlFragment); + GetTagsSqlFragment(history->GetTagsFolder(), "b.fk"_ns, mHasSearchTerms, + tagsSqlFragment); mQueryString = - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT b.fk, h.url, b.title AS page_title, " "h.rev_host, h.visit_count, h.last_visit_date, null, b.id, " "b.dateAdded, b.lastModified, b.parent, ") + tagsSqlFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( ", h.frecency, h.hidden, h.guid," "null, null, null, b.guid, b.position, b.type, b.fk " "FROM moz_bookmarks b " @@ -1269,7 +1267,7 @@ nsresult PlacesSQLQueryBuilder::SelectAsURI() { "(SELECT id FROM moz_bookmarks " "WHERE id = b.parent AND parent = ") + nsPrintfCString("%" PRId64, history->GetTagsFolder()) + - NS_LITERAL_CSTRING( + nsLiteralCString( ") " "AND NOT h.url_hash BETWEEN hash('place', 'prefix_lo') AND " "hash('place', 'prefix_hi') " @@ -1286,15 +1284,15 @@ nsresult PlacesSQLQueryBuilder::SelectAsVisit() { nsNavHistory* history = nsNavHistory::GetHistoryService(); NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY); nsAutoCString tagsSqlFragment; - GetTagsSqlFragment(history->GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), - mHasSearchTerms, tagsSqlFragment); + GetTagsSqlFragment(history->GetTagsFolder(), "h.id"_ns, mHasSearchTerms, + tagsSqlFragment); mQueryString = - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT h.id, h.url, h.title AS page_title, h.rev_host, " "h.visit_count, " "v.visit_date, null, null, null, null, null, ") + tagsSqlFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( ", h.frecency, h.hidden, h.guid, " "v.id, v.from_visit, v.visit_type " "FROM moz_places h " @@ -1353,10 +1351,10 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { // Today history->GetStringFromName("finduri-AgeInDays-is-0", dateName); // From start of today - sqlFragmentContainerBeginTime = NS_LITERAL_CSTRING( + sqlFragmentContainerBeginTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','utc')*1000000)"); // To now (tomorrow) - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','+1 " "day','utc')*1000000)"); // Search for the same timeframe. @@ -1367,11 +1365,11 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { // Yesterday history->GetStringFromName("finduri-AgeInDays-is-1", dateName); // From start of yesterday - sqlFragmentContainerBeginTime = NS_LITERAL_CSTRING( + sqlFragmentContainerBeginTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','-1 " "day','utc')*1000000)"); // To start of today - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','utc')*1000000)"); // Search for the same timeframe. sqlFragmentSearchBeginTime = sqlFragmentContainerBeginTime; @@ -1381,17 +1379,17 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { // Last 7 days history->GetAgeInDaysString(7, "finduri-AgeInDays-last-is", dateName); // From start of 7 days ago - sqlFragmentContainerBeginTime = NS_LITERAL_CSTRING( + sqlFragmentContainerBeginTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','-7 " "days','utc')*1000000)"); // To now (tomorrow) - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','+1 " "day','utc')*1000000)"); // This is an overlapped container, but we show it only if there are // visits older than yesterday. sqlFragmentSearchBeginTime = sqlFragmentContainerBeginTime; - sqlFragmentSearchEndTime = NS_LITERAL_CSTRING( + sqlFragmentSearchEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','-1 " "day','utc')*1000000)"); break; @@ -1399,17 +1397,17 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { // This month history->GetStringFromName("finduri-AgeInMonths-is-0", dateName); // From start of this month - sqlFragmentContainerBeginTime = NS_LITERAL_CSTRING( + sqlFragmentContainerBeginTime = nsLiteralCString( "(strftime('%s','now','localtime','start of " "month','utc')*1000000)"); // To now (tomorrow) - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','+1 " "day','utc')*1000000)"); // This is an overlapped container, but we show it only if there are // visits older than 7 days ago. sqlFragmentSearchBeginTime = sqlFragmentContainerBeginTime; - sqlFragmentSearchEndTime = NS_LITERAL_CSTRING( + sqlFragmentSearchEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of day','-7 " "days','utc')*1000000)"); break; @@ -1420,9 +1418,9 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { dateName); // From start of epoch sqlFragmentContainerBeginTime = - NS_LITERAL_CSTRING("(datetime(0, 'unixepoch')*1000000)"); + "(datetime(0, 'unixepoch')*1000000)"_ns; // To start of 6 months ago ( 5 months + this month). - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of month','-5 " "months','utc')*1000000)"); // Search for the same timeframe. @@ -1456,12 +1454,12 @@ nsresult PlacesSQLQueryBuilder::SelectAsDay() { } // From start of MonthIndex + 1 months ago - sqlFragmentContainerBeginTime = NS_LITERAL_CSTRING( + sqlFragmentContainerBeginTime = nsLiteralCString( "(strftime('%s','now','localtime','start of month','-"); sqlFragmentContainerBeginTime.AppendInt(MonthIndex); sqlFragmentContainerBeginTime.AppendLiteral(" months','utc')*1000000)"); // To start of MonthIndex months ago - sqlFragmentContainerEndTime = NS_LITERAL_CSTRING( + sqlFragmentContainerEndTime = nsLiteralCString( "(strftime('%s','now','localtime','start of month','-"); sqlFragmentContainerEndTime.AppendInt(MonthIndex - 1); sqlFragmentContainerEndTime.AppendLiteral(" months','utc')*1000000)"); @@ -1509,7 +1507,7 @@ nsresult PlacesSQLQueryBuilder::SelectAsSite() { NS_ENSURE_STATE(history); history->GetStringFromName("localhost", localFiles); - mAddParams.Put(NS_LITERAL_CSTRING("localhost"), localFiles); + mAddParams.Put("localhost"_ns, localFiles); // If there are additional conditions the query has to join on visits too. nsAutoCString visitsJoin; @@ -1595,22 +1593,20 @@ nsresult PlacesSQLQueryBuilder::SelectAsRoots() { nsAutoCString unfiledTitle; history->GetStringFromName("BookmarksToolbarFolderTitle", toolbarTitle); - mAddParams.Put(NS_LITERAL_CSTRING("BookmarksToolbarFolderTitle"), - toolbarTitle); + mAddParams.Put("BookmarksToolbarFolderTitle"_ns, toolbarTitle); history->GetStringFromName("BookmarksMenuFolderTitle", menuTitle); - mAddParams.Put(NS_LITERAL_CSTRING("BookmarksMenuFolderTitle"), menuTitle); + mAddParams.Put("BookmarksMenuFolderTitle"_ns, menuTitle); history->GetStringFromName("OtherBookmarksFolderTitle", unfiledTitle); - mAddParams.Put(NS_LITERAL_CSTRING("OtherBookmarksFolderTitle"), unfiledTitle); + mAddParams.Put("OtherBookmarksFolderTitle"_ns, unfiledTitle); nsAutoCString mobileString; if (Preferences::GetBool(MOBILE_BOOKMARKS_PREF, false)) { nsAutoCString mobileTitle; history->GetStringFromName("MobileBookmarksFolderTitle", mobileTitle); - mAddParams.Put(NS_LITERAL_CSTRING("MobileBookmarksFolderTitle"), - mobileTitle); + mAddParams.Put("MobileBookmarksFolderTitle"_ns, mobileTitle); - mobileString = NS_LITERAL_CSTRING( + mobileString = nsLiteralCString( "," "(null, 'place:parent=" MOBILE_ROOT_GUID "', :MobileBookmarksFolderTitle, null, null, null, " @@ -1619,7 +1615,7 @@ nsresult PlacesSQLQueryBuilder::SelectAsRoots() { } mQueryString = - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT * FROM (" "VALUES(null, 'place:parent=" TOOLBAR_ROOT_GUID "', :BookmarksToolbarFolderTitle, null, null, null, " @@ -1630,7 +1626,7 @@ nsresult PlacesSQLQueryBuilder::SelectAsRoots() { "(null, 'place:parent=" UNFILED_ROOT_GUID "', :OtherBookmarksFolderTitle, null, null, null, " "null, null, 0, 0, null, null, null, null, 'unfiled____v', null) ") + - mobileString + NS_LITERAL_CSTRING(")"); + mobileString + ")"_ns; return NS_OK; } @@ -1645,14 +1641,13 @@ nsresult PlacesSQLQueryBuilder::SelectAsLeftPane() { nsAutoCString allBookmarksTitle; history->GetStringFromName("OrganizerQueryHistory", historyTitle); - mAddParams.Put(NS_LITERAL_CSTRING("OrganizerQueryHistory"), historyTitle); + mAddParams.Put("OrganizerQueryHistory"_ns, historyTitle); history->GetStringFromName("OrganizerQueryDownloads", downloadsTitle); - mAddParams.Put(NS_LITERAL_CSTRING("OrganizerQueryDownloads"), downloadsTitle); + mAddParams.Put("OrganizerQueryDownloads"_ns, downloadsTitle); history->GetStringFromName("TagsFolderTitle", tagsTitle); - mAddParams.Put(NS_LITERAL_CSTRING("TagsFolderTitle"), tagsTitle); + mAddParams.Put("TagsFolderTitle"_ns, tagsTitle); history->GetStringFromName("OrganizerQueryAllBookmarks", allBookmarksTitle); - mAddParams.Put(NS_LITERAL_CSTRING("OrganizerQueryAllBookmarks"), - allBookmarksTitle); + mAddParams.Put("OrganizerQueryAllBookmarks"_ns, allBookmarksTitle); mQueryString = nsPrintfCString( "SELECT * FROM (" @@ -1684,14 +1679,13 @@ nsresult PlacesSQLQueryBuilder::Where() { nsAutoCString additionalPlacesConditions; if (!mIncludeHidden) { - additionalPlacesConditions += NS_LITERAL_CSTRING("AND hidden = 0 "); + additionalPlacesConditions += "AND hidden = 0 "_ns; } if (mQueryType == nsINavHistoryQueryOptions::QUERY_TYPE_HISTORY) { // last_visit_date is updated for any kind of visit, so it's a good // indicator whether the page has visits. - additionalPlacesConditions += - NS_LITERAL_CSTRING("AND last_visit_date NOTNULL "); + additionalPlacesConditions += "AND last_visit_date NOTNULL "_ns; } if (mResultType == nsINavHistoryQueryOptions::RESULTS_AS_URI && @@ -1745,9 +1739,9 @@ nsresult PlacesSQLQueryBuilder::OrderBy() { // Ensure sorting does not change based on tables status. if (mResultType == nsINavHistoryQueryOptions::RESULTS_AS_URI) { if (mQueryType == nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS) - mQueryString += NS_LITERAL_CSTRING(" ORDER BY b.id ASC "); + mQueryString += " ORDER BY b.id ASC "_ns; else if (mQueryType == nsINavHistoryQueryOptions::QUERY_TYPE_HISTORY) - mQueryString += NS_LITERAL_CSTRING(" ORDER BY h.id ASC "); + mQueryString += " ORDER BY h.id ASC "_ns; } break; case nsINavHistoryQueryOptions::SORT_BY_TITLE_ASCENDING: @@ -1835,7 +1829,7 @@ void PlacesSQLQueryBuilder::OrderByTextColumnIndexDesc(int32_t aIndex) { nsresult PlacesSQLQueryBuilder::Limit() { if (mUseLimit && mMaxResults > 0) { - mQueryString += NS_LITERAL_CSTRING(" LIMIT "); + mQueryString += " LIMIT "_ns; mQueryString.AppendInt(mMaxResults); mQueryString.Append(' '); } @@ -1863,8 +1857,8 @@ nsresult nsNavHistory::ConstructQueryString( bool hasSearchTerms = !aQuery->SearchTerms().IsEmpty(); nsAutoCString tagsSqlFragment; - GetTagsSqlFragment(GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), - hasSearchTerms, tagsSqlFragment); + GetTagsSqlFragment(GetTagsFolder(), "h.id"_ns, hasSearchTerms, + tagsSqlFragment); if (IsOptimizableHistoryQuery( aQuery, aOptions, @@ -1875,12 +1869,12 @@ nsresult nsNavHistory::ConstructQueryString( // Generate an optimized query for the history menu and the old most visited // bookmark that was inserted into profiles. queryString = - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT h.id, h.url, h.title AS page_title, h.rev_host, " "h.visit_count, h.last_visit_date, " "null, null, null, null, null, ") + tagsSqlFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( ", h.frecency, h.hidden, h.guid, " "null, null, null " "FROM moz_places h " @@ -1890,7 +1884,7 @@ nsresult nsNavHistory::ConstructQueryString( "AND visit_type NOT IN ") + nsPrintfCString("(0,%d,%d) ", nsINavHistoryService::TRANSITION_EMBED, nsINavHistoryService::TRANSITION_FRAMED_LINK) + - NS_LITERAL_CSTRING( + nsLiteralCString( "LIMIT 1) " "{QUERY_OPTIONS} "); @@ -2535,34 +2529,33 @@ nsresult nsNavHistory::BindQueryClauseParameters( if (NS_SUCCEEDED(aQuery->GetHasBeginTime(&hasIt)) && hasIt) { PRTime time = NormalizeTime(aQuery->BeginTimeReference(), aQuery->BeginTime()); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("begin_time"), time); + rv = statement->BindInt64ByName("begin_time"_ns, time); NS_ENSURE_SUCCESS(rv, rv); } // end time if (NS_SUCCEEDED(aQuery->GetHasEndTime(&hasIt)) && hasIt) { PRTime time = NormalizeTime(aQuery->EndTimeReference(), aQuery->EndTime()); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("end_time"), time); + rv = statement->BindInt64ByName("end_time"_ns, time); NS_ENSURE_SUCCESS(rv, rv); } // search terms if (!aQuery->SearchTerms().IsEmpty()) { - rv = statement->BindStringByName(NS_LITERAL_CSTRING("search_string"), - aQuery->SearchTerms()); + rv = statement->BindStringByName("search_string"_ns, aQuery->SearchTerms()); NS_ENSURE_SUCCESS(rv, rv); } // min and max visit count int32_t visits = aQuery->MinVisits(); if (visits >= 0) { - rv = statement->BindInt32ByName(NS_LITERAL_CSTRING("min_visits"), visits); + rv = statement->BindInt32ByName("min_visits"_ns, visits); NS_ENSURE_SUCCESS(rv, rv); } visits = aQuery->MaxVisits(); if (visits >= 0) { - rv = statement->BindInt32ByName(NS_LITERAL_CSTRING("max_visits"), visits); + rv = statement->BindInt32ByName("max_visits"_ns, visits); NS_ENSURE_SUCCESS(rv, rv); } @@ -2572,8 +2565,7 @@ nsresult nsNavHistory::BindQueryClauseParameters( GetReversedHostname(NS_ConvertUTF8toUTF16(aQuery->Domain()), revDomain); if (aQuery->DomainIsHost()) { - rv = statement->BindStringByName(NS_LITERAL_CSTRING("domain_lower"), - revDomain); + rv = statement->BindStringByName("domain_lower"_ns, revDomain); NS_ENSURE_SUCCESS(rv, rv); } else { // for "mozilla.org" do query >= "gro.allizom." AND < "gro.allizom/" @@ -2581,27 +2573,24 @@ nsresult nsNavHistory::BindQueryClauseParameters( // index (using SUBSTRING() causes indexes to be discarded). NS_ASSERTION(revDomain[revDomain.Length() - 1] == '.', "Invalid rev. host"); - rv = statement->BindStringByName(NS_LITERAL_CSTRING("domain_lower"), - revDomain); + rv = statement->BindStringByName("domain_lower"_ns, revDomain); NS_ENSURE_SUCCESS(rv, rv); revDomain.Truncate(revDomain.Length() - 1); revDomain.Append(char16_t('/')); - rv = statement->BindStringByName(NS_LITERAL_CSTRING("domain_upper"), - revDomain); + rv = statement->BindStringByName("domain_upper"_ns, revDomain); NS_ENSURE_SUCCESS(rv, rv); } } // URI if (aQuery->Uri()) { - rv = URIBinder::Bind(statement, NS_LITERAL_CSTRING("uri"), aQuery->Uri()); + rv = URIBinder::Bind(statement, "uri"_ns, aQuery->Uri()); NS_ENSURE_SUCCESS(rv, rv); } // annotation if (!aQuery->Annotation().IsEmpty()) { - rv = statement->BindUTF8StringByName(NS_LITERAL_CSTRING("anno"), - aQuery->Annotation()); + rv = statement->BindUTF8StringByName("anno"_ns, aQuery->Annotation()); NS_ENSURE_SUCCESS(rv, rv); } @@ -2617,12 +2606,10 @@ nsresult nsNavHistory::BindQueryClauseParameters( NS_ENSURE_SUCCESS(rv, rv); } int64_t tagsFolder = GetTagsFolder(); - rv = statement->BindInt64ByName(NS_LITERAL_CSTRING("tags_folder"), - tagsFolder); + rv = statement->BindInt64ByName("tags_folder"_ns, tagsFolder); NS_ENSURE_SUCCESS(rv, rv); if (!aQuery->TagsAreNot()) { - rv = statement->BindInt32ByName(NS_LITERAL_CSTRING("tag_count"), - tags.Length()); + rv = statement->BindInt32ByName("tag_count"_ns, tags.Length()); NS_ENSURE_SUCCESS(rv, rv); } } @@ -3079,8 +3066,7 @@ nsresult nsNavHistory::VisitIdToResultNode(int64_t visitId, nsNavHistoryQueryOptions* aOptions, nsNavHistoryResultNode** aResult) { nsAutoCString tagsFragment; - GetTagsSqlFragment(GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), true, - tagsFragment); + GetTagsSqlFragment(GetTagsFolder(), "h.id"_ns, true, tagsFragment); nsCOMPtr statement; switch (aOptions->ResultType()) { @@ -3088,30 +3074,30 @@ nsresult nsNavHistory::VisitIdToResultNode(int64_t visitId, // visit query - want exact visit time // Should match kGetInfoIndex_* (see GetQueryResults) statement = mDB->GetStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT h.id, h.url, h.title, h.rev_host, h.visit_count, " "v.visit_date, null, null, null, null, null, ") + tagsFragment + - NS_LITERAL_CSTRING(", h.frecency, h.hidden, h.guid, " - "v.id, v.from_visit, v.visit_type " - "FROM moz_places h " - "JOIN moz_historyvisits v ON h.id = v.place_id " - "WHERE v.id = :visit_id ")); + nsLiteralCString(", h.frecency, h.hidden, h.guid, " + "v.id, v.from_visit, v.visit_type " + "FROM moz_places h " + "JOIN moz_historyvisits v ON h.id = v.place_id " + "WHERE v.id = :visit_id ")); break; case nsNavHistoryQueryOptions::RESULTS_AS_URI: // URL results - want last visit time // Should match kGetInfoIndex_* (see GetQueryResults) statement = mDB->GetStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT h.id, h.url, h.title, h.rev_host, h.visit_count, " "h.last_visit_date, null, null, null, null, null, ") + tagsFragment + - NS_LITERAL_CSTRING(", h.frecency, h.hidden, h.guid, " - "null, null, null " - "FROM moz_places h " - "JOIN moz_historyvisits v ON h.id = v.place_id " - "WHERE v.id = :visit_id ")); + nsLiteralCString(", h.frecency, h.hidden, h.guid, " + "null, null, null " + "FROM moz_places h " + "JOIN moz_historyvisits v ON h.id = v.place_id " + "WHERE v.id = :visit_id ")); break; default: @@ -3122,8 +3108,7 @@ nsresult nsNavHistory::VisitIdToResultNode(int64_t visitId, NS_ENSURE_STATE(statement); mozStorageStatementScoper scoper(statement); - nsresult rv = - statement->BindInt64ByName(NS_LITERAL_CSTRING("visit_id"), visitId); + nsresult rv = statement->BindInt64ByName("visit_id"_ns, visitId); NS_ENSURE_SUCCESS(rv, rv); bool hasMore = false; @@ -3144,25 +3129,23 @@ nsresult nsNavHistory::BookmarkIdToResultNode( int64_t aBookmarkId, nsNavHistoryQueryOptions* aOptions, nsNavHistoryResultNode** aResult) { nsAutoCString tagsFragment; - GetTagsSqlFragment(GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), true, - tagsFragment); + GetTagsSqlFragment(GetTagsFolder(), "h.id"_ns, true, tagsFragment); // Should match kGetInfoIndex_* nsCOMPtr stmt = mDB->GetStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT b.fk, h.url, b.title, " "h.rev_host, h.visit_count, h.last_visit_date, null, b.id, " "b.dateAdded, b.lastModified, b.parent, ") + tagsFragment + - NS_LITERAL_CSTRING(", h.frecency, h.hidden, h.guid, " - "null, null, null, b.guid, b.position, b.type, b.fk " - "FROM moz_bookmarks b " - "JOIN moz_places h ON b.fk = h.id " - "WHERE b.id = :item_id ")); + nsLiteralCString(", h.frecency, h.hidden, h.guid, " + "null, null, null, b.guid, b.position, b.type, b.fk " + "FROM moz_bookmarks b " + "JOIN moz_places h ON b.fk = h.id " + "WHERE b.id = :item_id ")); NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = - stmt->BindInt64ByName(NS_LITERAL_CSTRING("item_id"), aBookmarkId); + nsresult rv = stmt->BindInt64ByName("item_id"_ns, aBookmarkId); NS_ENSURE_SUCCESS(rv, rv); bool hasMore = false; @@ -3185,15 +3168,14 @@ nsresult nsNavHistory::URIToResultNode(nsIURI* aURI, nsNavHistoryQueryOptions* aOptions, nsNavHistoryResultNode** aResult) { nsAutoCString tagsFragment; - GetTagsSqlFragment(GetTagsFolder(), NS_LITERAL_CSTRING("h.id"), true, - tagsFragment); + GetTagsSqlFragment(GetTagsFolder(), "h.id"_ns, true, tagsFragment); // Should match kGetInfoIndex_* nsCOMPtr stmt = mDB->GetStatement( - NS_LITERAL_CSTRING("SELECT h.id, :page_url, COALESCE(b.title, h.title), " - "h.rev_host, h.visit_count, h.last_visit_date, null, " - "b.id, b.dateAdded, b.lastModified, b.parent, ") + + nsLiteralCString("SELECT h.id, :page_url, COALESCE(b.title, h.title), " + "h.rev_host, h.visit_count, h.last_visit_date, null, " + "b.id, b.dateAdded, b.lastModified, b.parent, ") + tagsFragment + - NS_LITERAL_CSTRING( + nsLiteralCString( ", h.frecency, h.hidden, h.guid, " "null, null, null, b.guid, b.position, b.type, b.fk " "FROM moz_places h " @@ -3202,7 +3184,7 @@ nsresult nsNavHistory::URIToResultNode(nsIURI* aURI, NS_ENSURE_STATE(stmt); mozStorageStatementScoper scoper(stmt); - nsresult rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), aURI); + nsresult rv = URIBinder::Bind(stmt, "page_url"_ns, aURI); NS_ENSURE_SUCCESS(rv, rv); bool hasMore = false; @@ -3366,16 +3348,14 @@ nsresult nsNavHistory::UpdateFrecency(int64_t aPlaceId) { ") " "WHERE id = :page_id"); NS_ENSURE_STATE(updateFrecencyStmt); - nsresult rv = updateFrecencyStmt->BindInt64ByName( - NS_LITERAL_CSTRING("page_id"), aPlaceId); + nsresult rv = updateFrecencyStmt->BindInt64ByName("page_id"_ns, aPlaceId); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr updateHiddenStmt = mDB->GetAsyncStatement( "UPDATE moz_places " "SET hidden = 0 " "WHERE id = :page_id AND frecency <> 0"); NS_ENSURE_STATE(updateHiddenStmt); - rv = updateHiddenStmt->BindInt64ByName(NS_LITERAL_CSTRING("page_id"), - aPlaceId); + rv = updateHiddenStmt->BindInt64ByName("page_id"_ns, aPlaceId); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr conn = mDB->MainConn(); diff --git a/toolkit/components/places/nsNavHistory.h b/toolkit/components/places/nsNavHistory.h index 286056c28a3a..8457ed312ce1 100644 --- a/toolkit/components/places/nsNavHistory.h +++ b/toolkit/components/places/nsNavHistory.h @@ -551,13 +551,13 @@ class nsNavHistory final : public nsSupportsWeakReference, /* Returns true if the given URI represents a history query. */ inline bool IsQueryURI(const nsCString& uri) { - return StringBeginsWith(uri, NS_LITERAL_CSTRING(PLACES_URI_PREFIX)); + return StringBeginsWith(uri, nsLiteralCString(PLACES_URI_PREFIX)); } /* Extracts the query string from a query URI. */ inline const nsDependentCSubstring QueryURIToQuery(const nsCString& uri) { NS_ASSERTION(IsQueryURI(uri), "should only be called for query URIs"); - return Substring(uri, NS_LITERAL_CSTRING(PLACES_URI_PREFIX).Length()); + return Substring(uri, nsLiteralCString(PLACES_URI_PREFIX).Length()); } #endif // nsNavHistory_h_ diff --git a/toolkit/components/places/nsNavHistoryQuery.cpp b/toolkit/components/places/nsNavHistoryQuery.cpp index dd89c16d8fdb..384bbeb2029a 100644 --- a/toolkit/components/places/nsNavHistoryQuery.cpp +++ b/toolkit/components/places/nsNavHistoryQuery.cpp @@ -165,10 +165,10 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, query->GetHasBeginTime(&hasIt); if (hasIt) { AppendInt64KeyValueIfNonzero(queryString, - NS_LITERAL_CSTRING(QUERYKEY_BEGIN_TIME), query, + nsLiteralCString(QUERYKEY_BEGIN_TIME), query, &nsINavHistoryQuery::GetBeginTime); AppendUint32KeyValueIfNonzero( - queryString, NS_LITERAL_CSTRING(QUERYKEY_BEGIN_TIME_REFERENCE), query, + queryString, nsLiteralCString(QUERYKEY_BEGIN_TIME_REFERENCE), query, &nsINavHistoryQuery::GetBeginTimeReference); } @@ -176,10 +176,10 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, query->GetHasEndTime(&hasIt); if (hasIt) { AppendInt64KeyValueIfNonzero(queryString, - NS_LITERAL_CSTRING(QUERYKEY_END_TIME), query, + nsLiteralCString(QUERYKEY_END_TIME), query, &nsINavHistoryQuery::GetEndTime); AppendUint32KeyValueIfNonzero( - queryString, NS_LITERAL_CSTRING(QUERYKEY_END_TIME_REFERENCE), query, + queryString, nsLiteralCString(QUERYKEY_END_TIME_REFERENCE), query, &nsINavHistoryQuery::GetEndTimeReference); } @@ -192,7 +192,7 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, return NS_ERROR_OUT_OF_MEMORY; AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_SEARCH_TERMS "="); + queryString += nsLiteralCString(QUERYKEY_SEARCH_TERMS "="); queryString += escapedTerms; } @@ -213,7 +213,7 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, // only bookmarked AppendBoolKeyValueIfTrue(queryString, - NS_LITERAL_CSTRING(QUERYKEY_ONLY_BOOKMARKED), query, + nsLiteralCString(QUERYKEY_ONLY_BOOKMARKED), query, &nsINavHistoryQuery::GetOnlyBookmarked); // domain (+ is host), only call if hasDomain, which means non-IsVoid @@ -221,7 +221,7 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, // which is valid if (!query->Domain().IsVoid()) { AppendBoolKeyValueIfTrue(queryString, - NS_LITERAL_CSTRING(QUERYKEY_DOMAIN_IS_HOST), query, + nsLiteralCString(QUERYKEY_DOMAIN_IS_HOST), query, &nsINavHistoryQuery::GetDomainIsHost); const nsCString& domain = query->Domain(); nsCString escapedDomain; @@ -267,7 +267,7 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, const nsTArray& parents = query->Parents(); for (uint32_t i = 0; i < parents.Length(); ++i) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_PARENT "="); + queryString += nsLiteralCString(QUERYKEY_PARENT "="); queryString += parents[i]; } @@ -279,76 +279,76 @@ nsNavHistory::QueryToQueryString(nsINavHistoryQuery* aQuery, return NS_ERROR_OUT_OF_MEMORY; AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_TAG "="); + queryString += nsLiteralCString(QUERYKEY_TAG "="); queryString += escapedTag; } - AppendBoolKeyValueIfTrue(queryString, NS_LITERAL_CSTRING(QUERYKEY_NOTTAGS), + AppendBoolKeyValueIfTrue(queryString, nsLiteralCString(QUERYKEY_NOTTAGS), query, &nsINavHistoryQuery::GetTagsAreNot); // transitions const nsTArray& transitions = query->Transitions(); for (uint32_t i = 0; i < transitions.Length(); ++i) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_TRANSITION "="); + queryString += nsLiteralCString(QUERYKEY_TRANSITION "="); AppendInt64(queryString, transitions[i]); } // sorting if (options->SortingMode() != nsINavHistoryQueryOptions::SORT_BY_NONE) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_SORT "="); + queryString += nsLiteralCString(QUERYKEY_SORT "="); AppendInt16(queryString, options->SortingMode()); } // result type if (options->ResultType() != nsINavHistoryQueryOptions::RESULTS_AS_URI) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_RESULT_TYPE "="); + queryString += nsLiteralCString(QUERYKEY_RESULT_TYPE "="); AppendInt16(queryString, options->ResultType()); } // exclude items if (options->ExcludeItems()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_EXCLUDE_ITEMS "=1"); + queryString += nsLiteralCString(QUERYKEY_EXCLUDE_ITEMS "=1"); } // exclude queries if (options->ExcludeQueries()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_EXCLUDE_QUERIES "=1"); + queryString += nsLiteralCString(QUERYKEY_EXCLUDE_QUERIES "=1"); } // expand queries if (!options->ExpandQueries()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_EXPAND_QUERIES "=0"); + queryString += nsLiteralCString(QUERYKEY_EXPAND_QUERIES "=0"); } // include hidden if (options->IncludeHidden()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_INCLUDE_HIDDEN "=1"); + queryString += nsLiteralCString(QUERYKEY_INCLUDE_HIDDEN "=1"); } // max results if (options->MaxResults()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_MAX_RESULTS "="); + queryString += nsLiteralCString(QUERYKEY_MAX_RESULTS "="); AppendInt32(queryString, options->MaxResults()); } // queryType if (options->QueryType() != nsINavHistoryQueryOptions::QUERY_TYPE_HISTORY) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_QUERY_TYPE "="); + queryString += nsLiteralCString(QUERYKEY_QUERY_TYPE "="); AppendInt16(queryString, options->QueryType()); } // async enabled if (options->AsyncEnabled()) { AppendAmpersandIfNonempty(queryString); - queryString += NS_LITERAL_CSTRING(QUERYKEY_ASYNC_ENABLED "=1"); + queryString += nsLiteralCString(QUERYKEY_ASYNC_ENABLED "=1"); } aQueryString.AssignLiteral("place:"); diff --git a/toolkit/components/places/nsNavHistoryResult.cpp b/toolkit/components/places/nsNavHistoryResult.cpp index af710967392e..4227cf99fa42 100644 --- a/toolkit/components/places/nsNavHistoryResult.cpp +++ b/toolkit/components/places/nsNavHistoryResult.cpp @@ -380,10 +380,10 @@ nsNavHistoryResultNode::GetTags(nsAString& aTags) { nsNavHistory* history = nsNavHistory::GetHistoryService(); NS_ENSURE_STATE(history); - nsresult rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("tags_folder"), - history->GetTagsFolder()); + nsresult rv = + stmt->BindInt64ByName("tags_folder"_ns, history->GetTagsFolder()); NS_ENSURE_SUCCESS(rv, rv); - rv = URIBinder::Bind(stmt, NS_LITERAL_CSTRING("page_url"), mURI); + rv = URIBinder::Bind(stmt, "page_url"_ns, mURI); NS_ENSURE_SUCCESS(rv, rv); bool hasTags = false; @@ -3144,7 +3144,7 @@ nsresult nsNavHistoryQueryResultNode::OnMobilePrefChanged(bool newValue) { // We're removing the mobile folder, so find it. int32_t existingIndex; - FindChildByGuid(NS_LITERAL_CSTRING(MOBILE_BOOKMARKS_VIRTUAL_GUID), + FindChildByGuid(nsLiteralCString(MOBILE_BOOKMARKS_VIRTUAL_GUID), &existingIndex); if (existingIndex == -1) { @@ -3375,10 +3375,9 @@ nsNavHistoryFolderResultNode::OnItemMoved( RESTART_AND_RETURN_IF_ASYNC_PENDING(); bool excludeItems = mOptions->ExcludeItems(); - if (excludeItems && - (aItemType == nsINavBookmarksService::TYPE_SEPARATOR || - (aItemType == nsINavBookmarksService::TYPE_BOOKMARK && - !StringBeginsWith(aURI, NS_LITERAL_CSTRING("place:"))))) { + if (excludeItems && (aItemType == nsINavBookmarksService::TYPE_SEPARATOR || + (aItemType == nsINavBookmarksService::TYPE_BOOKMARK && + !StringBeginsWith(aURI, "place:"_ns)))) { // This is a bookmark or a separator, so we don't need to handle this if // we're excluding items. return NS_OK; diff --git a/toolkit/components/places/nsPlacesIndexes.h b/toolkit/components/places/nsPlacesIndexes.h index 5c47e33271b9..7654a8b3f940 100644 --- a/toolkit/components/places/nsPlacesIndexes.h +++ b/toolkit/components/places/nsPlacesIndexes.h @@ -7,9 +7,9 @@ #ifndef nsPlacesIndexes_h__ #define nsPlacesIndexes_h__ -#define CREATE_PLACES_IDX(__name, __table, __columns, __type) \ - NS_LITERAL_CSTRING("CREATE " __type " INDEX IF NOT EXISTS " __table \ - "_" __name " ON " __table " (" __columns ")") +#define CREATE_PLACES_IDX(__name, __table, __columns, __type) \ + nsLiteralCString("CREATE " __type " INDEX IF NOT EXISTS " __table "_" __name \ + " ON " __table " (" __columns ")") /** * moz_places diff --git a/toolkit/components/places/nsPlacesTables.h b/toolkit/components/places/nsPlacesTables.h index b44ea2ac5261..408ad833f6a9 100644 --- a/toolkit/components/places/nsPlacesTables.h +++ b/toolkit/components/places/nsPlacesTables.h @@ -8,7 +8,7 @@ #define __nsPlacesTables_h__ #define CREATE_MOZ_PLACES \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_places ( " \ " id INTEGER PRIMARY KEY" \ ", url LONGVARCHAR" \ @@ -28,7 +28,7 @@ ")") #define CREATE_MOZ_HISTORYVISITS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_historyvisits (" \ " id INTEGER PRIMARY KEY" \ ", from_visit INTEGER" \ @@ -39,7 +39,7 @@ ")") #define CREATE_MOZ_INPUTHISTORY \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_inputhistory (" \ " place_id INTEGER NOT NULL" \ ", input LONGVARCHAR NOT NULL" \ @@ -50,7 +50,7 @@ // Note: flags, expiration, type, dateAdded and lastModified should be // considered deprecated but are kept to ease backwards compatibility. #define CREATE_MOZ_ANNOS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_annos (" \ " id INTEGER PRIMARY KEY" \ ", place_id INTEGER NOT NULL" \ @@ -64,14 +64,14 @@ ")") #define CREATE_MOZ_ANNO_ATTRIBUTES \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_anno_attributes (" \ " id INTEGER PRIMARY KEY" \ ", name VARCHAR(32) UNIQUE NOT NULL" \ ")") #define CREATE_MOZ_ITEMS_ANNOS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_items_annos (" \ " id INTEGER PRIMARY KEY" \ ", item_id INTEGER NOT NULL" \ @@ -85,7 +85,7 @@ ")") #define CREATE_MOZ_BOOKMARKS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_bookmarks (" \ " id INTEGER PRIMARY KEY" \ ", type INTEGER" \ @@ -132,14 +132,14 @@ // never set up, we'll never write new tombstones, since all bookmarks will stay // in SYNC_STATUS_NEW. #define CREATE_MOZ_BOOKMARKS_DELETED \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_bookmarks_deleted (" \ " guid TEXT PRIMARY KEY" \ ", dateRemoved INTEGER NOT NULL DEFAULT 0" \ ")") #define CREATE_MOZ_KEYWORDS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_keywords (" \ " id INTEGER PRIMARY KEY AUTOINCREMENT" \ ", keyword TEXT UNIQUE" \ @@ -148,7 +148,7 @@ ")") #define CREATE_MOZ_ORIGINS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_origins ( " \ "id INTEGER PRIMARY KEY, " \ "prefix TEXT NOT NULL, " \ @@ -160,7 +160,7 @@ // Note: this should be kept up-to-date with the definition in // nsPlacesAutoComplete.js. #define CREATE_MOZ_OPENPAGES_TEMP \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TABLE moz_openpages_temp (" \ " url TEXT" \ ", userContextId INTEGER" \ @@ -174,7 +174,7 @@ // will take care of updating the moz_origins table for every new origin. See // CREATE_PLACES_AFTERINSERT_TRIGGER in nsPlacestriggers.h for details. #define CREATE_UPDATEORIGINSINSERT_TEMP \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TABLE moz_updateoriginsinsert_temp ( " \ "place_id INTEGER PRIMARY KEY, " \ "prefix TEXT NOT NULL, " \ @@ -188,7 +188,7 @@ // When rows are added to this table, moz_places.origin_id may be null. That's // why this table uses prefix + host as its primary key, not origin_id. #define CREATE_UPDATEORIGINSDELETE_TEMP \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TABLE moz_updateoriginsdelete_temp ( " \ "prefix TEXT NOT NULL, " \ "host TEXT NOT NULL, " \ @@ -203,7 +203,7 @@ // When rows are added to this table, moz_places.origin_id may be null. That's // why this table uses prefix + host as its primary key, not origin_id. #define CREATE_UPDATEORIGINSUPDATE_TEMP \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TABLE moz_updateoriginsupdate_temp ( " \ "prefix TEXT NOT NULL, " \ "host TEXT NOT NULL, " \ @@ -218,7 +218,7 @@ // created with a different places.sqlite (not just in case of a user messing // up with the profile, but also in case of corruption). #define CREATE_MOZ_PAGES_W_ICONS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_pages_w_icons ( " \ "id INTEGER PRIMARY KEY, " \ "page_url TEXT NOT NULL, " \ @@ -231,7 +231,7 @@ // We are considering squared icons for simplicity, so storing only one size. // For svg payloads, width will be set to 65535 (UINT16_MAX). #define CREATE_MOZ_ICONS \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_icons ( " \ "id INTEGER PRIMARY KEY, " \ "icon_url TEXT NOT NULL, " \ @@ -247,7 +247,7 @@ // Each page can have multiple icons, and each icon can be used by multiple // pages. #define CREATE_MOZ_ICONS_TO_PAGES \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_icons_to_pages ( " \ "page_id INTEGER NOT NULL, " \ "icon_id INTEGER NOT NULL, " \ @@ -260,7 +260,7 @@ // the sync IDs for the bookmarks and history collections in this table, and the // last sync time for history. #define CREATE_MOZ_META \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TABLE moz_meta (" \ "key TEXT PRIMARY KEY, " \ "value NOT NULL" \ diff --git a/toolkit/components/places/nsPlacesTriggers.h b/toolkit/components/places/nsPlacesTriggers.h index af8947da92da..054c7188becd 100644 --- a/toolkit/components/places/nsPlacesTriggers.h +++ b/toolkit/components/places/nsPlacesTriggers.h @@ -24,7 +24,7 @@ * table changes. */ # define CREATE_HISTORYVISITS_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_historyvisits_afterinsert_v2_trigger " \ "AFTER INSERT ON moz_historyvisits FOR EACH ROW " \ "BEGIN " \ @@ -38,7 +38,7 @@ "END") # define CREATE_HISTORYVISITS_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_historyvisits_afterdelete_v2_trigger " \ "AFTER DELETE ON moz_historyvisits FOR EACH ROW " \ "BEGIN " \ @@ -99,7 +99,7 @@ // This trigger runs on inserts into moz_places. # define CREATE_PLACES_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_places_afterinsert_trigger " \ "AFTER INSERT ON moz_places FOR EACH ROW " \ "BEGIN " \ @@ -113,7 +113,7 @@ // This trigger corresponds to the previous trigger. It runs on deletes on // moz_updateoriginsinsert_temp -- logically, after inserts on moz_places. # define CREATE_UPDATEORIGINSINSERT_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_updateoriginsinsert_afterdelete_trigger " \ "AFTER DELETE ON moz_updateoriginsinsert_temp FOR EACH ROW " \ "BEGIN " \ @@ -137,7 +137,7 @@ // This trigger runs on deletes on moz_places. # define CREATE_PLACES_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_places_afterdelete_trigger " \ "AFTER DELETE ON moz_places FOR EACH ROW " \ "BEGIN " \ @@ -152,7 +152,7 @@ // This trigger corresponds to the previous trigger. It runs on deletes on // moz_updateoriginsdelete_temp -- logically, after deletes on moz_places. # define CREATE_UPDATEORIGINSDELETE_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_updateoriginsdelete_afterdelete_trigger " \ "AFTER DELETE ON moz_updateoriginsdelete_temp FOR EACH ROW " \ "BEGIN " \ @@ -187,7 +187,7 @@ // moz_place, which would be expensive; and (2) decay does not change the // ordering of frecencies since all frecencies decay by the same percentage. # define CREATE_PLACES_AFTERUPDATE_FRECENCY_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_places_afterupdate_frecency_trigger " \ "AFTER UPDATE OF frecency ON moz_places FOR EACH ROW " \ "WHEN NOT is_frecency_decaying() " \ @@ -203,7 +203,7 @@ // moz_updateoriginsupdate_temp -- logically, after updates to // moz_places.frecency. # define CREATE_UPDATEORIGINSUPDATE_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_updateoriginsupdate_afterdelete_trigger " \ "AFTER DELETE ON moz_updateoriginsupdate_temp FOR EACH ROW " \ "BEGIN " \ @@ -224,7 +224,7 @@ * nsPlacesAutoComplete.js */ # define CREATE_REMOVEOPENPAGE_CLEANUP_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMPORARY TRIGGER moz_openpages_temp_afterupdate_trigger " \ "AFTER UPDATE OF open_count ON moz_openpages_temp FOR EACH ROW " \ "WHEN NEW.open_count = 0 " \ @@ -235,7 +235,7 @@ "END") # define CREATE_BOOKMARKS_FOREIGNCOUNT_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_bookmarks_foreign_count_afterdelete_trigger " \ "AFTER DELETE ON moz_bookmarks FOR EACH ROW " \ "BEGIN " \ @@ -245,7 +245,7 @@ "END") # define CREATE_BOOKMARKS_FOREIGNCOUNT_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_bookmarks_foreign_count_afterinsert_trigger " \ "AFTER INSERT ON moz_bookmarks FOR EACH ROW " \ "BEGIN " \ @@ -257,7 +257,7 @@ "END") # define CREATE_BOOKMARKS_FOREIGNCOUNT_AFTERUPDATE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_bookmarks_foreign_count_afterupdate_trigger " \ "AFTER UPDATE OF fk, syncChangeCounter ON moz_bookmarks FOR EACH ROW " \ "BEGIN " \ @@ -272,7 +272,7 @@ "END") # define CREATE_KEYWORDS_FOREIGNCOUNT_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_keywords_foreign_count_afterdelete_trigger " \ "AFTER DELETE ON moz_keywords FOR EACH ROW " \ "BEGIN " \ @@ -282,7 +282,7 @@ "END") # define CREATE_KEYWORDS_FOREIGNCOUNT_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_keywords_foreign_count_afterinsert_trigger " \ "AFTER INSERT ON moz_keywords FOR EACH ROW " \ "BEGIN " \ @@ -292,7 +292,7 @@ "END") # define CREATE_KEYWORDS_FOREIGNCOUNT_AFTERUPDATE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_keywords_foreign_count_afterupdate_trigger " \ "AFTER UPDATE OF place_id ON moz_keywords FOR EACH ROW " \ "BEGIN " \ @@ -305,7 +305,7 @@ "END") # define CREATE_ICONS_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_icons_afterinsert_v1_trigger " \ "AFTER INSERT ON moz_icons FOR EACH ROW " \ "BEGIN " \ @@ -313,7 +313,7 @@ "END") # define CREATE_BOOKMARKS_DELETED_AFTERINSERT_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_bookmarks_deleted_afterinsert_v1_trigger " \ "AFTER INSERT ON moz_bookmarks_deleted FOR EACH ROW " \ "BEGIN " \ @@ -321,7 +321,7 @@ "END") # define CREATE_BOOKMARKS_DELETED_AFTERDELETE_TRIGGER \ - NS_LITERAL_CSTRING( \ + nsLiteralCString( \ "CREATE TEMP TRIGGER moz_bookmarks_deleted_afterdelete_v1_trigger " \ "AFTER DELETE ON moz_bookmarks_deleted FOR EACH ROW " \ "BEGIN " \ diff --git a/toolkit/components/places/tests/gtest/places_test_harness.h b/toolkit/components/places/tests/gtest/places_test_harness.h index 5f16b8b8526d..0a067a8145d5 100644 --- a/toolkit/components/places/tests/gtest/places_test_harness.h +++ b/toolkit/components/places/tests/gtest/places_test_harness.h @@ -209,7 +209,7 @@ void do_get_place(nsIURI* aURI, PlaceRecord& result) { do_check_success(rv); rv = dbConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id, hidden, typed, visit_count, guid FROM moz_places " "WHERE url_hash = hash(?1) AND url = ?1"), getter_AddRefs(stmt)); @@ -249,7 +249,7 @@ void do_get_lastVisit(int64_t placeId, VisitRecord& result) { nsCOMPtr stmt; nsresult rv = dbConn->CreateStatement( - NS_LITERAL_CSTRING( + nsLiteralCString( "SELECT id, from_visit, visit_type FROM moz_historyvisits " "WHERE place_id=?1 " "LIMIT 1"), @@ -280,12 +280,11 @@ void do_wait_async_updates() { nsCOMPtr db = do_get_db(); nsCOMPtr stmt; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("BEGIN EXCLUSIVE"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("BEGIN EXCLUSIVE"_ns, getter_AddRefs(stmt)); nsCOMPtr pending; (void)stmt->ExecuteAsync(nullptr, getter_AddRefs(pending)); - db->CreateAsyncStatement(NS_LITERAL_CSTRING("COMMIT"), getter_AddRefs(stmt)); + db->CreateAsyncStatement("COMMIT"_ns, getter_AddRefs(stmt)); RefPtr spinner = new PlacesAsyncStatementSpinner(); (void)stmt->ExecuteAsync(spinner, getter_AddRefs(pending)); diff --git a/toolkit/components/places/tests/gtest/test_IHistory.cpp b/toolkit/components/places/tests/gtest/test_IHistory.cpp index 3a579eed8dce..3a51f3e9900e 100644 --- a/toolkit/components/places/tests/gtest/test_IHistory.cpp +++ b/toolkit/components/places/tests/gtest/test_IHistory.cpp @@ -33,7 +33,7 @@ void expect_no_visit(nsLinkState aState) { already_AddRefed new_test_uri() { // Create a unique spec. static int32_t specNumber = 0; - nsCString spec = NS_LITERAL_CSTRING("http://mozilla.org/"); + nsCString spec = "http://mozilla.org/"_ns; spec.AppendInt(specNumber++); // Create the URI for the spec. @@ -103,8 +103,7 @@ void test_wait_checkpoint() { // and cause concurrent readers to access an older checkpoint. nsCOMPtr db = do_get_db(); nsCOMPtr stmt; - db->CreateAsyncStatement(NS_LITERAL_CSTRING("SELECT 1"), - getter_AddRefs(stmt)); + db->CreateAsyncStatement("SELECT 1"_ns, getter_AddRefs(stmt)); RefPtr spinner = new PlacesAsyncStatementSpinner(); nsCOMPtr pending; diff --git a/toolkit/components/printingui/nsPrintProgress.cpp b/toolkit/components/printingui/nsPrintProgress.cpp index e6f4408dcc13..2a8dd2c3873f 100644 --- a/toolkit/components/printingui/nsPrintProgress.cpp +++ b/toolkit/components/printingui/nsPrintProgress.cpp @@ -87,10 +87,10 @@ NS_IMETHODIMP nsPrintProgress::OpenProgressDialog( // Open the dialog. RefPtr newBC; - rv = piOwnerWindow->OpenDialog( - NS_ConvertASCIItoUTF16(dialogURL), NS_LITERAL_STRING("_blank"), - NS_LITERAL_STRING("chrome,titlebar,dependent,centerscreen"), array, - getter_AddRefs(newBC)); + rv = piOwnerWindow->OpenDialog(NS_ConvertASCIItoUTF16(dialogURL), + u"_blank"_ns, + u"chrome,titlebar,dependent,centerscreen"_ns, + array, getter_AddRefs(newBC)); } return rv; diff --git a/toolkit/components/prompts/docs/nsIPromptService.rst b/toolkit/components/prompts/docs/nsIPromptService.rst index 2c7eccd643e0..a39ef73f1992 100644 --- a/toolkit/components/prompts/docs/nsIPromptService.rst +++ b/toolkit/components/prompts/docs/nsIPromptService.rst @@ -123,9 +123,9 @@ C++ Sync nsresult rv = promptSvc->confirmCheck(mBrowsingContext, nsIPromptService::MODAL_TYPE_TAB, - NS_LITERAL_CSTRING("My Title") - NS_LITERAL_CSTRING("Hello, World!"), - NS_LITERAL_CSTRING("Check this box if you agree"), + "My Title"_ns + "Hello, World!"_ns, + "Check this box if you agree"_ns, &checked, &ok); // ok is the boolean indicating if the user clicked "ok" (true) or @@ -154,9 +154,9 @@ C++ Async // As opposed to the sync case, here we pass the checked flag by value nsresult rv = promptSvc->confirmCheckAsync(mBrowsingContext, - nsIPromptService::MODAL_TYPE_TAB, NS_LITERAL_CSTRING("My Title"), - NS_LITERAL_CSTRING("Hello, World!"), - NS_LITERAL_CSTRING("Check this box if you agree"), + nsIPromptService::MODAL_TYPE_TAB, "My Title"_ns, + "Hello, World!"_ns, + "Check this box if you agree"_ns, checked, promise); // Attach a promise handler @@ -179,8 +179,8 @@ Then, in your promise handler callback function: bool ok; bool checked; - propBag->GetPropertyAsBool(NS_LITERAL_STRING("ok"), &ok); - propBag->GetPropertyAsBool(NS_LITERAL_STRING("checked"), &checked); + propBag->GetPropertyAsBool(u"ok"_ns, &ok); + propBag->GetPropertyAsBool(u"checked"_ns, &checked); // ok is the boolean indicating if the user clicked "ok" (true) or // "cancel" (false). diff --git a/toolkit/components/reputationservice/ApplicationReputation.cpp b/toolkit/components/reputationservice/ApplicationReputation.cpp index 51a3b51bd4ee..10bb27f3c575 100644 --- a/toolkit/components/reputationservice/ApplicationReputation.cpp +++ b/toolkit/components/reputationservice/ApplicationReputation.cpp @@ -948,35 +948,35 @@ ClientDownloadRequest::DownloadType PendingLookup::GetDownloadType( // From // https://cs.chromium.org/chromium/src/chrome/common/safe_browsing/download_protection_util.cc?l=17 - if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".zip"))) { + if (StringEndsWith(aFilename, ".zip"_ns)) { return ClientDownloadRequest::ZIPPED_EXECUTABLE; - } else if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".apk"))) { + } else if (StringEndsWith(aFilename, ".apk"_ns)) { return ClientDownloadRequest::ANDROID_APK; - } else if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".app")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".applescript")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".cdr")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dart")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dc42")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".diskcopy42")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dmg")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dmgpart")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dvdr")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".img")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".imgpart")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".iso")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".mpkg")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".ndif")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".osas")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".osax")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".pkg")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".scpt")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".scptd")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".seplugin")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".smi")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".sparsebundle")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".sparseimage")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".toast")) || - StringEndsWith(aFilename, NS_LITERAL_CSTRING(".udif"))) { + } else if (StringEndsWith(aFilename, ".app"_ns) || + StringEndsWith(aFilename, ".applescript"_ns) || + StringEndsWith(aFilename, ".cdr"_ns) || + StringEndsWith(aFilename, ".dart"_ns) || + StringEndsWith(aFilename, ".dc42"_ns) || + StringEndsWith(aFilename, ".diskcopy42"_ns) || + StringEndsWith(aFilename, ".dmg"_ns) || + StringEndsWith(aFilename, ".dmgpart"_ns) || + StringEndsWith(aFilename, ".dvdr"_ns) || + StringEndsWith(aFilename, ".img"_ns) || + StringEndsWith(aFilename, ".imgpart"_ns) || + StringEndsWith(aFilename, ".iso"_ns) || + StringEndsWith(aFilename, ".mpkg"_ns) || + StringEndsWith(aFilename, ".ndif"_ns) || + StringEndsWith(aFilename, ".osas"_ns) || + StringEndsWith(aFilename, ".osax"_ns) || + StringEndsWith(aFilename, ".pkg"_ns) || + StringEndsWith(aFilename, ".scpt"_ns) || + StringEndsWith(aFilename, ".scptd"_ns) || + StringEndsWith(aFilename, ".seplugin"_ns) || + StringEndsWith(aFilename, ".smi"_ns) || + StringEndsWith(aFilename, ".sparsebundle"_ns) || + StringEndsWith(aFilename, ".sparseimage"_ns) || + StringEndsWith(aFilename, ".toast"_ns) || + StringEndsWith(aFilename, ".udif"_ns)) { return ClientDownloadRequest::MAC_EXECUTABLE; } @@ -1657,8 +1657,7 @@ nsresult PendingLookup::SendRemoteQueryInternal(Reason& aReason) { if (LOG_ENABLED()) { nsAutoCString serializedStr(serialized.c_str(), serialized.length()); - serializedStr.ReplaceSubstring(NS_LITERAL_CSTRING("\0"), - NS_LITERAL_CSTRING("\\0")); + serializedStr.ReplaceSubstring("\0"_ns, "\\0"_ns); LOG(("Serialized protocol buffer [this = %p]: (length=%d) %s", this, serializedStr.Length(), serializedStr.get())); @@ -1698,8 +1697,8 @@ nsresult PendingLookup::SendRemoteQueryInternal(Reason& aReason) { NS_ENSURE_SUCCESS(rv, rv); rv = uploadChannel->ExplicitSetUploadStream( - sstream, NS_LITERAL_CSTRING("application/octet-stream"), - serialized.size(), NS_LITERAL_CSTRING("POST"), false); + sstream, "application/octet-stream"_ns, serialized.size(), "POST"_ns, + false); NS_ENSURE_SUCCESS(rv, rv); uint32_t timeoutMs = diff --git a/toolkit/components/resistfingerprinting/nsRFPService.cpp b/toolkit/components/resistfingerprinting/nsRFPService.cpp index ebf8bf9a069f..a3e7e129d053 100644 --- a/toolkit/components/resistfingerprinting/nsRFPService.cpp +++ b/toolkit/components/resistfingerprinting/nsRFPService.cpp @@ -813,7 +813,7 @@ void nsRFPService::UpdateRFPPref() { // We will not touch the TZ value if 'privacy.resistFingerprinting' is false // during the time of initialization. if (!mInitialTZValue.IsEmpty()) { - nsAutoCString tzValue = NS_LITERAL_CSTRING("TZ=") + mInitialTZValue; + nsAutoCString tzValue = "TZ="_ns + mInitialTZValue; static char* tz = nullptr; // If the tz has been set before, we free it first since it will be @@ -1057,7 +1057,7 @@ bool nsRFPService::GetSpoofedCode(const dom::Document* aDoc, // it's a right key. if (aKeyboardEvent->mLocation == dom::KeyboardEvent_Binding::DOM_KEY_LOCATION_RIGHT && - StringEndsWith(aOut, NS_LITERAL_STRING("Left"))) { + StringEndsWith(aOut, u"Left"_ns)) { aOut.ReplaceLiteral(aOut.Length() - 4, 4, u"Right"); } diff --git a/toolkit/components/satchel/nsFormFillController.cpp b/toolkit/components/satchel/nsFormFillController.cpp index 0dd0be8315e6..b1fa7318c16a 100644 --- a/toolkit/components/satchel/nsFormFillController.cpp +++ b/toolkit/components/satchel/nsFormFillController.cpp @@ -597,10 +597,10 @@ nsFormFillController::OnTextEntered(Event* aEvent, bool itemWasSelected, IgnoredErrorResult ignored; RefPtr event = mFocusedInput->OwnerDoc()->CreateEvent( - NS_LITERAL_STRING("Events"), CallerType::System, ignored); + u"Events"_ns, CallerType::System, ignored); NS_ENSURE_STATE(event); - event->InitEvent(NS_LITERAL_STRING("DOMAutoComplete"), true, true); + event->InitEvent(u"DOMAutoComplete"_ns, true, true); // XXXjst: We mark this event as a trusted event, it's up to the // callers of this to ensure that it's only called from trusted diff --git a/toolkit/components/sessionstore/SessionStoreListener.cpp b/toolkit/components/sessionstore/SessionStoreListener.cpp index 0c34339de8e1..9396e67dbbed 100644 --- a/toolkit/components/sessionstore/SessionStoreListener.cpp +++ b/toolkit/components/sessionstore/SessionStoreListener.cpp @@ -216,18 +216,16 @@ nsresult TabListener::Init() { if (!eventTarget) { return NS_OK; } - eventTarget->AddSystemEventListener(NS_LITERAL_STRING("mozvisualscroll"), - this, false); - eventTarget->AddSystemEventListener(NS_LITERAL_STRING("input"), this, false); + eventTarget->AddSystemEventListener(u"mozvisualscroll"_ns, this, false); + eventTarget->AddSystemEventListener(u"input"_ns, this, false); if (mSHistoryInParent) { - eventTarget->AddSystemEventListener(NS_LITERAL_STRING("DOMTitleChanged"), - this, false); + eventTarget->AddSystemEventListener(u"DOMTitleChanged"_ns, this, false); } mEventListenerRegistered = true; - eventTarget->AddSystemEventListener( - NS_LITERAL_STRING("MozSessionStorageChanged"), this, false); + eventTarget->AddSystemEventListener(u"MozSessionStorageChanged"_ns, this, + false); mStorageChangeListenerRegistered = true; return NS_OK; } @@ -789,8 +787,8 @@ void TabListener::ResetStorageChangeListener() { if (!eventTarget) { return; } - eventTarget->AddSystemEventListener( - NS_LITERAL_STRING("MozSessionStorageChanged"), this, false); + eventTarget->AddSystemEventListener(u"MozSessionStorageChanged"_ns, this, + false); mStorageChangeListenerRegistered = true; } @@ -801,8 +799,8 @@ void TabListener::RemoveStorageChangeListener() { nsCOMPtr eventTarget = GetEventTarget(); if (eventTarget) { - eventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("MozSessionStorageChanged"), this, false); + eventTarget->RemoveSystemEventListener(u"MozSessionStorageChanged"_ns, this, + false); mStorageChangeListenerRegistered = false; } } @@ -820,19 +818,18 @@ void TabListener::RemoveListeners() { nsCOMPtr eventTarget = GetEventTarget(); if (eventTarget) { if (mEventListenerRegistered) { - eventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("mozvisualscroll"), this, false); - eventTarget->RemoveSystemEventListener(NS_LITERAL_STRING("input"), this, + eventTarget->RemoveSystemEventListener(u"mozvisualscroll"_ns, this, false); + eventTarget->RemoveSystemEventListener(u"input"_ns, this, false); if (mSHistoryInParent) { - eventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("DOMTitleChanged"), this, false); + eventTarget->RemoveSystemEventListener(u"DOMTitleChanged"_ns, this, + false); } mEventListenerRegistered = false; } if (mStorageChangeListenerRegistered) { - eventTarget->RemoveSystemEventListener( - NS_LITERAL_STRING("MozSessionStorageChanged"), this, false); + eventTarget->RemoveSystemEventListener(u"MozSessionStorageChanged"_ns, + this, false); mStorageChangeListenerRegistered = false; } } diff --git a/toolkit/components/sessionstore/SessionStoreUtils.cpp b/toolkit/components/sessionstore/SessionStoreUtils.cpp index 7ef35ee80cb4..930e26326307 100644 --- a/toolkit/components/sessionstore/SessionStoreUtils.cpp +++ b/toolkit/components/sessionstore/SessionStoreUtils.cpp @@ -414,7 +414,7 @@ static void AppendValueToCollectedData( nsTArray& aXPathVals, nsTArray& aIdVals) { CollectedInputDataValue entry; - entry.type = NS_LITERAL_STRING("bool"); + entry.type = u"bool"_ns; entry.value = AsVariant(aValue); AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals, aIdVals); @@ -437,7 +437,7 @@ static void AppendValueToCollectedData( nsTArray& aXPathVals, nsTArray& aIdVals) { CollectedInputDataValue entry; - entry.type = NS_LITERAL_STRING("string"); + entry.type = u"string"_ns; entry.value = AsVariant(aValue); AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals, aIdVals); @@ -465,7 +465,7 @@ static void AppendValueToCollectedData( uint16_t& aNumId, nsTArray& aXPathVals, nsTArray& aIdVals) { CollectedInputDataValue entry; - entry.type = NS_LITERAL_STRING("singleSelect"); + entry.type = u"singleSelect"_ns; entry.value = AsVariant(aValue); AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals, aIdVals); @@ -509,7 +509,7 @@ static void AppendValueToCollectedData( nsTArray& aXPathVals, nsTArray& aIdVals) { CollectedInputDataValue entry; - entry.type = NS_LITERAL_STRING("string"); + entry.type = u"string"_ns; entry.value = AsVariant(aValue); AppendEntryToCollectedData(aNode, aId, entry, aNumXPath, aNumId, aXPathVals, aIdVals); @@ -560,8 +560,8 @@ template void SessionStoreUtils::CollectFromTextAreaElement(Document& aDocument, uint16_t& aGeneratedCount, ArgsT&&... args) { - RefPtr textlist = NS_GetContentList( - &aDocument, kNameSpaceID_XHTML, NS_LITERAL_STRING("textarea")); + RefPtr textlist = + NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"textarea"_ns); uint32_t length = textlist->Length(true); for (uint32_t i = 0; i < length; ++i) { MOZ_ASSERT(textlist->Item(i), "null item in node list!"); @@ -599,8 +599,8 @@ template void SessionStoreUtils::CollectFromInputElement(Document& aDocument, uint16_t& aGeneratedCount, ArgsT&&... args) { - RefPtr inputlist = NS_GetContentList( - &aDocument, kNameSpaceID_XHTML, NS_LITERAL_STRING("input")); + RefPtr inputlist = + NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"input"_ns); uint32_t length = inputlist->Length(true); for (uint32_t i = 0; i < length; ++i) { MOZ_ASSERT(inputlist->Item(i), "null item in node list!"); @@ -648,8 +648,8 @@ void SessionStoreUtils::CollectFromInputElement(Document& aDocument, if (rv.Failed() || result.Length() == 0) { continue; } - AppendValueToCollectedData(input, id, NS_LITERAL_STRING("file"), result, - aGeneratedCount, std::forward(args)...); + AppendValueToCollectedData(input, id, u"file"_ns, result, aGeneratedCount, + std::forward(args)...); } else { nsString value; input->GetValue(value, CallerType::System); @@ -673,8 +673,8 @@ template void SessionStoreUtils::CollectFromSelectElement(Document& aDocument, uint16_t& aGeneratedCount, ArgsT&&... args) { - RefPtr selectlist = NS_GetContentList( - &aDocument, kNameSpaceID_XHTML, NS_LITERAL_STRING("select")); + RefPtr selectlist = + NS_GetContentList(&aDocument, kNameSpaceID_XHTML, u"select"_ns); uint32_t length = selectlist->Length(true); for (uint32_t i = 0; i < length; ++i) { MOZ_ASSERT(selectlist->Item(i), "null item in node list!"); @@ -730,9 +730,8 @@ void SessionStoreUtils::CollectFromSelectElement(Document& aDocument, continue; } - AppendValueToCollectedData( - select, id, NS_LITERAL_STRING("multipleSelect"), selectslist, - aGeneratedCount, std::forward(args)...); + AppendValueToCollectedData(select, id, u"multipleSelect"_ns, selectslist, + aGeneratedCount, std::forward(args)...); } } } diff --git a/toolkit/components/startup/nsAppStartup.cpp b/toolkit/components/startup/nsAppStartup.cpp index a84b77b8ff82..4eebb0e55ab3 100644 --- a/toolkit/components/startup/nsAppStartup.cpp +++ b/toolkit/components/startup/nsAppStartup.cpp @@ -183,26 +183,25 @@ nsresult nsAppStartup::Init() { // This last event is only interesting to us for xperf-based measures // Initialize interaction with profiler - mProbesManager = new ProbeManager( - kApplicationTracingCID, NS_LITERAL_CSTRING("Application startup probe")); + mProbesManager = + new ProbeManager(kApplicationTracingCID, "Application startup probe"_ns); // Note: The operation is meant mostly for in-house profiling. // Therefore, we do not warn if probes manager cannot be initialized if (mProbesManager) { mPlacesInitCompleteProbe = mProbesManager->GetProbe( - kPlacesInitCompleteCID, NS_LITERAL_CSTRING("places-init-complete")); + kPlacesInitCompleteCID, "places-init-complete"_ns); NS_WARNING_ASSERTION(mPlacesInitCompleteProbe, "Cannot initialize probe 'places-init-complete'"); mSessionWindowRestoredProbe = mProbesManager->GetProbe( - kSessionStoreWindowRestoredCID, - NS_LITERAL_CSTRING("sessionstore-windows-restored")); + kSessionStoreWindowRestoredCID, "sessionstore-windows-restored"_ns); NS_WARNING_ASSERTION( mSessionWindowRestoredProbe, "Cannot initialize probe 'sessionstore-windows-restored'"); - mXPCOMShutdownProbe = mProbesManager->GetProbe( - kXPCOMShutdownCID, NS_LITERAL_CSTRING("xpcom-shutdown")); + mXPCOMShutdownProbe = + mProbesManager->GetProbe(kXPCOMShutdownCID, "xpcom-shutdown"_ns); NS_WARNING_ASSERTION(mXPCOMShutdownProbe, "Cannot initialize probe 'xpcom-shutdown'"); diff --git a/toolkit/components/telemetry/core/Telemetry.cpp b/toolkit/components/telemetry/core/Telemetry.cpp index 30ed9970b36e..e4233014a353 100644 --- a/toolkit/components/telemetry/core/Telemetry.cpp +++ b/toolkit/components/telemetry/core/Telemetry.cpp @@ -323,8 +323,7 @@ nsresult GetFailedProfileLockFile(nsIFile** aFile, nsIFile* aProfileDir) { nsresult rv = aProfileDir->Clone(aFile); NS_ENSURE_SUCCESS(rv, rv); - (*aFile)->AppendNative( - NS_LITERAL_CSTRING("Telemetry.FailedProfileLocks.txt")); + (*aFile)->AppendNative("Telemetry.FailedProfileLocks.txt"_ns); return NS_OK; } @@ -414,7 +413,7 @@ static PathCharPtr GetShutdownTimeFileName() { NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mozFile)); if (!mozFile) return nullptr; - mozFile->AppendNative(NS_LITERAL_CSTRING("Telemetry.ShutdownTime.txt")); + mozFile->AppendNative("Telemetry.ShutdownTime.txt"_ns); gRecordedShutdownTimeFileName = NS_xstrdup(mozFile->NativePath().get()); } @@ -1215,16 +1214,14 @@ static void internal_initGlean() { } nsAutoCString osVersion; - rv = infoService->GetPropertyAsACString(NS_LITERAL_STRING("version"), - osVersion); + rv = infoService->GetPropertyAsACString(u"version"_ns, osVersion); if (NS_FAILED(rv)) { NS_WARNING("Can't get OS version. FOG will not be initialized."); return; } nsAutoCString architecture; - rv = infoService->GetPropertyAsACString(NS_LITERAL_STRING("arch"), - architecture); + rv = infoService->GetPropertyAsACString(u"arch"_ns, architecture); if (NS_FAILED(rv)) { NS_WARNING("Can't get architecture. FOG will not be initialized."); return; @@ -2136,7 +2133,7 @@ void SetProfileDir(nsIFile* aProfD) { if (NS_FAILED(rv)) { return; } - sTelemetryIOObserver->AddPath(profDirPath, NS_LITERAL_STRING("{profile}")); + sTelemetryIOObserver->AddPath(profDirPath, u"{profile}"_ns); } // Scalar API C++ Endpoints diff --git a/toolkit/components/telemetry/core/TelemetryEvent.cpp b/toolkit/components/telemetry/core/TelemetryEvent.cpp index ce9b07a6a9a3..bc5aa350a68f 100644 --- a/toolkit/components/telemetry/core/TelemetryEvent.cpp +++ b/toolkit/components/telemetry/core/TelemetryEvent.cpp @@ -334,7 +334,7 @@ nsCString GetCategory(const StaticMutexAutoLock& lock, } if (!gDynamicEventInfo) { - return NS_LITERAL_CSTRING(""); + return ""_ns; } return (*gDynamicEventInfo)[eventKey.id].category; @@ -777,7 +777,7 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, // Check value argument. if ((optional_argc > 0) && !aValue.isNull() && !aValue.isString()) { LogToBrowserConsole(nsIScriptError::warningFlag, - NS_LITERAL_STRING("Invalid type for value parameter.")); + u"Invalid type for value parameter."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Value); return NS_OK; @@ -788,9 +788,8 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, if (aValue.isString()) { nsAutoJSString jsStr; if (!jsStr.init(cx, aValue)) { - LogToBrowserConsole( - nsIScriptError::warningFlag, - NS_LITERAL_STRING("Invalid string value for value parameter.")); + LogToBrowserConsole(nsIScriptError::warningFlag, + u"Invalid string value for value parameter."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Value); return NS_OK; @@ -800,8 +799,8 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, if (str.Length() > kMaxValueByteLength) { LogToBrowserConsole( nsIScriptError::warningFlag, - NS_LITERAL_STRING( - "Value parameter exceeds maximum string length, truncating.")); + nsLiteralString( + u"Value parameter exceeds maximum string length, truncating.")); TruncateToByteLength(str, kMaxValueByteLength); } value = mozilla::Some(str); @@ -810,7 +809,7 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, // Check extra argument. if ((optional_argc > 1) && !aExtra.isNull() && !aExtra.isObject()) { LogToBrowserConsole(nsIScriptError::warningFlag, - NS_LITERAL_STRING("Invalid type for extra parameter.")); + u"Invalid type for extra parameter."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Extra); return NS_OK; @@ -823,7 +822,7 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, JS::Rooted ids(cx, JS::IdVector(cx)); if (!JS_Enumerate(cx, obj, &ids)) { LogToBrowserConsole(nsIScriptError::warningFlag, - NS_LITERAL_STRING("Failed to enumerate object.")); + u"Failed to enumerate object."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Extra); return NS_OK; @@ -834,8 +833,8 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, if (!key.init(cx, ids[i])) { LogToBrowserConsole( nsIScriptError::warningFlag, - NS_LITERAL_STRING( - "Extra dictionary should only contain string keys.")); + nsLiteralString( + u"Extra dictionary should only contain string keys.")); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Extra); return NS_OK; @@ -844,7 +843,7 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, JS::Rooted value(cx); if (!JS_GetPropertyById(cx, obj, ids[i], &value)) { LogToBrowserConsole(nsIScriptError::warningFlag, - NS_LITERAL_STRING("Failed to get extra property.")); + u"Failed to get extra property."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Extra); return NS_OK; @@ -852,9 +851,8 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, nsAutoJSString jsStr; if (!value.isString() || !jsStr.init(cx, value)) { - LogToBrowserConsole( - nsIScriptError::warningFlag, - NS_LITERAL_STRING("Extra properties should have string values.")); + LogToBrowserConsole(nsIScriptError::warningFlag, + u"Extra properties should have string values."_ns); mozilla::Telemetry::AccumulateCategorical( LABELS_TELEMETRY_EVENT_RECORDING_ERROR::Extra); return NS_OK; @@ -864,8 +862,8 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, if (str.Length() > kMaxExtraValueByteLength) { LogToBrowserConsole( nsIScriptError::warningFlag, - NS_LITERAL_STRING( - "Extra value exceeds maximum string length, truncating.")); + nsLiteralString( + u"Extra value exceeds maximum string length, truncating.")); TruncateToByteLength(str, kMaxExtraValueByteLength); } @@ -926,7 +924,7 @@ nsresult TelemetryEvent::RecordEvent(const nsACString& aCategory, } case RecordEventResult::StorageLimitReached: { LogToBrowserConsole(nsIScriptError::warningFlag, - NS_LITERAL_STRING("Event storage limit reached.")); + u"Event storage limit reached."_ns); nsCOMPtr serv = mozilla::services::GetObserverService(); if (serv) { @@ -1345,7 +1343,7 @@ void TelemetryEvent::SetEventRecordingEnabled(const nsACString& category, LogToBrowserConsole( nsIScriptError::warningFlag, NS_ConvertUTF8toUTF16( - NS_LITERAL_CSTRING( + nsLiteralCString( "Unknown category for SetEventRecordingEnabled: ") + category)); return; diff --git a/toolkit/components/telemetry/core/TelemetryHistogram.cpp b/toolkit/components/telemetry/core/TelemetryHistogram.cpp index 0040a5ccf337..1c028b14bc53 100644 --- a/toolkit/components/telemetry/core/TelemetryHistogram.cpp +++ b/toolkit/components/telemetry/core/TelemetryHistogram.cpp @@ -1229,7 +1229,7 @@ nsresult KeyedHistogram::Add(const nsCString& key, uint32_t sample, base::Histogram* histogram; if (mSingleStore != nullptr) { - histogram = GetHistogram(NS_LITERAL_CSTRING("main"), key); + histogram = GetHistogram("main"_ns, key); if (!histogram) { MOZ_ASSERT(false, "Missing histogram in single store."); return NS_ERROR_FAILURE; @@ -1666,8 +1666,8 @@ bool internal_JSHistogram_CoerceValue(JSContext* aCx, if (aHistogramType != nsITelemetry::HISTOGRAM_CATEGORICAL) { LogToBrowserConsole( nsIScriptError::errorFlag, - NS_LITERAL_STRING( - "String argument only allowed for categorical histogram")); + nsLiteralString( + u"String argument only allowed for categorical histogram")); return false; } @@ -1675,7 +1675,7 @@ bool internal_JSHistogram_CoerceValue(JSContext* aCx, nsAutoJSString label; if (!label.init(aCx, aElement)) { LogToBrowserConsole(nsIScriptError::errorFlag, - NS_LITERAL_STRING("Invalid string parameter")); + u"Invalid string parameter"_ns); return false; } @@ -1690,8 +1690,7 @@ bool internal_JSHistogram_CoerceValue(JSContext* aCx, return false; } } else if (!(aElement.isNumber() || aElement.isBoolean())) { - LogToBrowserConsole(nsIScriptError::errorFlag, - NS_LITERAL_STRING("Argument not a number")); + LogToBrowserConsole(nsIScriptError::errorFlag, u"Argument not a number"_ns); return false; } else if (aElement.isNumber() && aElement.toNumber() > UINT32_MAX) { // Clamp large numerical arguments to aValue's acceptable values. @@ -1700,12 +1699,11 @@ bool internal_JSHistogram_CoerceValue(JSContext* aCx, aValue = UINT32_MAX; #ifdef DEBUG LogToBrowserConsole(nsIScriptError::errorFlag, - NS_LITERAL_STRING("Clamped large numeric value")); + u"Clamped large numeric value"_ns); #endif } else if (!JS::ToUint32(aCx, aElement, &aValue)) { - LogToBrowserConsole( - nsIScriptError::errorFlag, - NS_LITERAL_STRING("Failed to convert element to UInt32")); + LogToBrowserConsole(nsIScriptError::errorFlag, + u"Failed to convert element to UInt32"_ns); return false; } @@ -1733,8 +1731,8 @@ bool internal_JSHistogram_GetValueArray(JSContext* aCx, JS::CallArgs& args, if (!(aHistogramType == nsITelemetry::HISTOGRAM_COUNT)) { LogToBrowserConsole( nsIScriptError::errorFlag, - NS_LITERAL_STRING( - "Need at least one argument for non count type histogram")); + nsLiteralString( + u"Need at least one argument for non count type histogram")); return false; } @@ -1751,16 +1749,15 @@ bool internal_JSHistogram_GetValueArray(JSContext* aCx, JS::CallArgs& args, if (!isArray) { LogToBrowserConsole( nsIScriptError::errorFlag, - NS_LITERAL_STRING( - "The argument to accumulate can't be a non-array object")); + nsLiteralString( + u"The argument to accumulate can't be a non-array object")); return false; } uint32_t arrayLength = 0; if (!JS::GetArrayLength(aCx, arrayObj, &arrayLength)) { - LogToBrowserConsole( - nsIScriptError::errorFlag, - NS_LITERAL_STRING("Failed while trying to get array length")); + LogToBrowserConsole(nsIScriptError::errorFlag, + u"Failed while trying to get array length"_ns); return false; } @@ -2162,15 +2159,13 @@ bool internal_JSKeyedHistogram_Add(JSContext* cx, unsigned argc, // rather report failures using the console. args.rval().setUndefined(); if (args.length() < 1) { - LogToBrowserConsole(nsIScriptError::errorFlag, - NS_LITERAL_STRING("Expected one argument")); + LogToBrowserConsole(nsIScriptError::errorFlag, u"Expected one argument"_ns); return true; } nsAutoJSString key; if (!args[0].isString() || !key.init(cx, args[0])) { - LogToBrowserConsole(nsIScriptError::errorFlag, - NS_LITERAL_STRING("Not a string")); + LogToBrowserConsole(nsIScriptError::errorFlag, u"Not a string"_ns); return true; } @@ -2662,9 +2657,8 @@ nsresult TelemetryHistogram::Accumulate(const char* name, const nsCString& key, } if (keyNotAllowed) { - LogToBrowserConsole( - nsIScriptError::errorFlag, - NS_LITERAL_STRING("Key not allowed for this keyed histogram")); + LogToBrowserConsole(nsIScriptError::errorFlag, + u"Key not allowed for this keyed histogram"_ns); TelemetryScalar::Add(mozilla::Telemetry::ScalarID:: TELEMETRY_ACCUMULATE_UNKNOWN_HISTOGRAM_KEYS, NS_ConvertASCIItoUTF16(name), 1); @@ -3198,8 +3192,7 @@ nsresult TelemetryHistogram::SerializeHistograms(mozilla::JSONWriter& aWriter) { // record the right subset, so this will only return "prerelease" if // it was recorded. if (NS_FAILED(internal_GetHistogramsSnapshot( - locker, NS_LITERAL_CSTRING("main"), - nsITelemetry::DATASET_PRERELEASE_CHANNELS, + locker, "main"_ns, nsITelemetry::DATASET_PRERELEASE_CHANNELS, false /* aClearSubsession */, includeGPUProcess, false /* aFilterTest */, processHistArray))) { return NS_ERROR_FAILURE; @@ -3243,8 +3236,7 @@ nsresult TelemetryHistogram::SerializeKeyedHistograms( // record the right subset, so this will only return "prerelease" if // it was recorded. if (NS_FAILED(internal_GetKeyedHistogramsSnapshot( - locker, NS_LITERAL_CSTRING("main"), - nsITelemetry::DATASET_PRERELEASE_CHANNELS, + locker, "main"_ns, nsITelemetry::DATASET_PRERELEASE_CHANNELS, false /* aClearSubsession */, includeGPUProcess, false /* aFilterTest */, processHistArray))) { return NS_ERROR_FAILURE; @@ -3629,9 +3621,8 @@ nsresult TelemetryHistogram::DeserializeKeyedHistograms(JSContext* aCx, // Get data for the key we're looking for. base::Histogram* h = nullptr; - if (NS_FAILED(keyed->GetHistogram(NS_LITERAL_CSTRING("main"), - mozilla::Get<1>(histogramData), - &h))) { + if (NS_FAILED(keyed->GetHistogram( + "main"_ns, mozilla::Get<1>(histogramData), &h))) { continue; } MOZ_ASSERT(h); diff --git a/toolkit/components/telemetry/core/TelemetryScalar.cpp b/toolkit/components/telemetry/core/TelemetryScalar.cpp index 3802f8117970..6fcf41a1b6fd 100644 --- a/toolkit/components/telemetry/core/TelemetryScalar.cpp +++ b/toolkit/components/telemetry/core/TelemetryScalar.cpp @@ -3793,7 +3793,7 @@ nsresult TelemetryScalar::SerializeScalars(mozilla::JSONWriter& aWriter) { nsresult rv = internal_GetScalarSnapshot( locker, scalarsToReflect, nsITelemetry::DATASET_PRERELEASE_CHANNELS, false, /*aClearScalars*/ - NS_LITERAL_CSTRING("main")); + "main"_ns); if (NS_FAILED(rv)) { return rv; } @@ -3843,7 +3843,7 @@ nsresult TelemetryScalar::SerializeKeyedScalars(mozilla::JSONWriter& aWriter) { nsresult rv = internal_GetKeyedScalarSnapshot( locker, keyedScalarsToReflect, nsITelemetry::DATASET_PRERELEASE_CHANNELS, false, /*aClearScalars*/ - NS_LITERAL_CSTRING("main")); + "main"_ns); if (NS_FAILED(rv)) { return rv; } diff --git a/toolkit/components/telemetry/docs/collection/origin.rst b/toolkit/components/telemetry/docs/collection/origin.rst index 6032d92df252..0d0b211c71cf 100644 --- a/toolkit/components/telemetry/docs/collection/origin.rst +++ b/toolkit/components/telemetry/docs/collection/origin.rst @@ -70,7 +70,7 @@ Recording This C++ API records that a metric was true for a given origin. For instance, maybe the user visited a page in which content from ``example.net`` was blocked. -That call might look like ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Blocked, NS_LITERAL_CSTRING("example.net"))``. +That call might look like ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Blocked, "example.net"_ns)``. Snapshotting ------------ @@ -121,7 +121,7 @@ To improve Content Blocking's effectiveness we need to know these two "what's" o This means we need two metrics ``contentblocking.blocked`` and ``contentblocking.exempt`` (the "what's"), and a list of origins (the "wheres"). Say "example.net" was blocked and "example.com" was exempted from blocking. -Content Blocking calls ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Blocked, NS_LITERAL_CSTRING("example.net"))`` and ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Exempt, NS_LITERAL_CSTRING("example.com"))``. +Content Blocking calls ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Blocked, "example.net"_ns))`` and ``Telemetry::RecordOrigin(OriginMetricID::ContentBlocking_Exempt, "example.com"_ns)``. At this time a call to ``Telemetry.getOriginSnapshot()`` would return: diff --git a/toolkit/components/telemetry/docs/collection/scalars.rst b/toolkit/components/telemetry/docs/collection/scalars.rst index a36f6744141f..8c0b0b1b4abb 100644 --- a/toolkit/components/telemetry/docs/collection/scalars.rst +++ b/toolkit/components/telemetry/docs/collection/scalars.rst @@ -304,7 +304,7 @@ Native code can take advantage of Scalars as well, by including the ``Telemetry. Telemetry::ScalarSet(Telemetry::ScalarID::PROFILE_WAS_RESET, false); Telemetry::ScalarAdd(Telemetry::ScalarID::UI_DOWNLOAD_BUTTON_ACTIVATED, - NS_LITERAL_STRING("touchscreen"), 1); + u"touchscreen"_ns, 1); The ``ScalarID`` enum is automatically generated by the build process, with an example being available `here `_ . diff --git a/toolkit/components/telemetry/other/TelemetryIOInterposeObserver.cpp b/toolkit/components/telemetry/other/TelemetryIOInterposeObserver.cpp index ca90f7e1e0aa..b4fc5a35843a 100644 --- a/toolkit/components/telemetry/other/TelemetryIOInterposeObserver.cpp +++ b/toolkit/components/telemetry/other/TelemetryIOInterposeObserver.cpp @@ -15,7 +15,7 @@ TelemetryIOInterposeObserver::TelemetryIOInterposeObserver(nsIFile* aXreDir) nsAutoString xreDirPath; nsresult rv = aXreDir->GetPath(xreDirPath); if (NS_SUCCEEDED(rv)) { - AddPath(xreDirPath, NS_LITERAL_STRING("{xre}")); + AddPath(xreDirPath, u"{xre}"_ns); } } diff --git a/toolkit/components/telemetry/other/UntrustedModules.cpp b/toolkit/components/telemetry/other/UntrustedModules.cpp index 1e66d2c70fb9..dce8f9e30633 100644 --- a/toolkit/components/telemetry/other/UntrustedModules.cpp +++ b/toolkit/components/telemetry/other/UntrustedModules.cpp @@ -245,7 +245,7 @@ static bool SerializeEvent(JSContext* aCx, JS::MutableHandleValue aElement, nsDependentCString effectiveThreadName; if (aEvent.mThreadId == ::GetCurrentThreadId()) { - effectiveThreadName.Rebind(NS_LITERAL_CSTRING("Main Thread"), 0); + effectiveThreadName.Rebind("Main Thread"_ns, 0); } else { effectiveThreadName.Rebind(aEvent.mThreadName, 0); } @@ -310,7 +310,7 @@ static nsresult GetPerProcObject(JSContext* aCx, const IndexMap& aModuleIndices, JS::MutableHandleObject aObj) { nsDependentCString strProcType; if (aData.mProcessType == GeckoProcessType_Default) { - strProcType.Rebind(NS_LITERAL_CSTRING("browser"), 0); + strProcType.Rebind("browser"_ns, 0); } else { strProcType.Rebind(XRE_GeckoProcessTypeToString(aData.mProcessType)); } diff --git a/toolkit/components/telemetry/tests/gtest/TelemetryTestHelpers.cpp b/toolkit/components/telemetry/tests/gtest/TelemetryTestHelpers.cpp index c289f472c780..ff219ef3863c 100644 --- a/toolkit/components/telemetry/tests/gtest/TelemetryTestHelpers.cpp +++ b/toolkit/components/telemetry/tests/gtest/TelemetryTestHelpers.cpp @@ -298,13 +298,11 @@ void GetScalarsSnapshot(bool aKeyed, JSContext* aCx, nsresult rv; if (aKeyed) { - rv = telemetry->GetSnapshotForKeyedScalars(NS_LITERAL_CSTRING("main"), - false, false /* filter */, aCx, - &scalarsSnapshot); + rv = telemetry->GetSnapshotForKeyedScalars( + "main"_ns, false, false /* filter */, aCx, &scalarsSnapshot); } else { - rv = telemetry->GetSnapshotForScalars(NS_LITERAL_CSTRING("main"), false, - false /* filter */, aCx, - &scalarsSnapshot); + rv = telemetry->GetSnapshotForScalars("main"_ns, false, false /* filter */, + aCx, &scalarsSnapshot); } // Validate the snapshot. @@ -362,12 +360,11 @@ void GetSnapshots(JSContext* cx, nsCOMPtr mTelemetry, const char* name, JS::MutableHandleValue valueOut, bool is_keyed) { JS::RootedValue snapshots(cx); - nsresult rv = is_keyed ? mTelemetry->GetSnapshotForKeyedHistograms( - NS_LITERAL_CSTRING("main"), false, - false /* filter */, cx, &snapshots) - : mTelemetry->GetSnapshotForHistograms( - NS_LITERAL_CSTRING("main"), false, - false /* filter */, cx, &snapshots); + nsresult rv = is_keyed + ? mTelemetry->GetSnapshotForKeyedHistograms( + "main"_ns, false, false /* filter */, cx, &snapshots) + : mTelemetry->GetSnapshotForHistograms( + "main"_ns, false, false /* filter */, cx, &snapshots); JS::RootedValue snapshot(cx); GetProperty(cx, "parent", snapshots, &snapshot); diff --git a/toolkit/components/telemetry/tests/gtest/TestCounters.cpp b/toolkit/components/telemetry/tests/gtest/TestCounters.cpp index 2aad895f1758..2950500c3f4d 100644 --- a/toolkit/components/telemetry/tests/gtest/TestCounters.cpp +++ b/toolkit/components/telemetry/tests/gtest/TestCounters.cpp @@ -19,8 +19,8 @@ TEST_F(TelemetryTestFixture, AutoCounter) { const char* telemetryTestCountName = Telemetry::GetHistogramName(Telemetry::TELEMETRY_TEST_COUNT); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram { @@ -63,8 +63,8 @@ TEST_F(TelemetryTestFixture, AutoCounterUnderflow) { const char* telemetryTestCountName = Telemetry::GetHistogramName(Telemetry::TELEMETRY_TEST_COUNT); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram { @@ -99,8 +99,8 @@ TEST_F(TelemetryTestFixture, RuntimeAutoCounter) { const char* telemetryTestCountName = Telemetry::GetHistogramName(Telemetry::TELEMETRY_TEST_COUNT); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram { @@ -142,8 +142,8 @@ TEST_F(TelemetryTestFixture, RuntimeAutoCounterUnderflow) { const char* telemetryTestCountName = Telemetry::GetHistogramName(Telemetry::TELEMETRY_TEST_COUNT); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram { diff --git a/toolkit/components/telemetry/tests/gtest/TestHistograms.cpp b/toolkit/components/telemetry/tests/gtest/TestHistograms.cpp index c3a473265da1..5bb22dc3b568 100644 --- a/toolkit/components/telemetry/tests/gtest/TestHistograms.cpp +++ b/toolkit/components/telemetry/tests/gtest/TestHistograms.cpp @@ -21,8 +21,8 @@ TEST_F(TelemetryTestFixture, AccumulateCountHistogram) { ASSERT_STREQ(telemetryTestCountName, "TELEMETRY_TEST_COUNT") << "The histogram name is wrong"; - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_COUNT, kExpectedValue / 2); @@ -53,11 +53,11 @@ TEST_F(TelemetryTestFixture, AccumulateKeyedCountHistogram) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_COUNT"), true); + "TELEMETRY_TEST_KEYED_COUNT"_ns, true); // Accumulate data in the provided key within the histogram - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), kExpectedValue); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_COUNT, "sample"_ns, + kExpectedValue); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -91,19 +91,16 @@ TEST_F(TelemetryTestFixture, TestKeyedKeysHistogram) { JS::RootedValue rval(cx.GetJSContext()); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_KEYS"), true); + "TELEMETRY_TEST_KEYED_KEYS"_ns, true); // Test the accumulation on both the allowed and unallowed keys, using // the API that accepts histogram IDs. - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, - NS_LITERAL_CSTRING("not-allowed"), 1); - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, - NS_LITERAL_CSTRING("testkey"), 0); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, "not-allowed"_ns, + 1); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, "testkey"_ns, 0); // Do the same, using the API that accepts the histogram name as a string. - Telemetry::Accumulate("TELEMETRY_TEST_KEYED_KEYS", - NS_LITERAL_CSTRING("not-allowed"), 1); - Telemetry::Accumulate("TELEMETRY_TEST_KEYED_KEYS", - NS_LITERAL_CSTRING("CommonKey"), 1); + Telemetry::Accumulate("TELEMETRY_TEST_KEYED_KEYS", "not-allowed"_ns, 1); + Telemetry::Accumulate("TELEMETRY_TEST_KEYED_KEYS", "CommonKey"_ns, 1); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -158,7 +155,7 @@ TEST_F(TelemetryTestFixture, AccumulateCategoricalHistogram) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_CATEGORICAL"), false); + "TELEMETRY_TEST_CATEGORICAL"_ns, false); // Accumulate one unit into the categorical histogram with label // Telemetry::LABELS_TELEMETRY_TEST_CATEGORICAL::CommonLabel @@ -168,7 +165,7 @@ TEST_F(TelemetryTestFixture, AccumulateCategoricalHistogram) { // Accumulate another unit into the same categorical histogram using a string // label Telemetry::AccumulateCategorical(Telemetry::TELEMETRY_TEST_CATEGORICAL, - NS_LITERAL_CSTRING("CommonLabel")); + "CommonLabel"_ns); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -206,21 +203,20 @@ TEST_F(TelemetryTestFixture, AccumulateKeyedCategoricalHistogram) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_CATEGORICAL"), - true); + "TELEMETRY_TEST_KEYED_CATEGORICAL"_ns, true); // Accumulate one unit into the categorical histogram with label // Telemetry::LABELS_TELEMETRY_TEST_KEYED_CATEGORICAL::CommonLabel Telemetry::AccumulateCategoricalKeyed( - NS_LITERAL_CSTRING("sample"), + "sample"_ns, Telemetry::LABELS_TELEMETRY_TEST_KEYED_CATEGORICAL::CommonLabel); // Accumulate another unit into the same categorical histogram Telemetry::AccumulateCategoricalKeyed( - NS_LITERAL_CSTRING("sample"), + "sample"_ns, Telemetry::LABELS_TELEMETRY_TEST_KEYED_CATEGORICAL::CommonLabel); // Accumulate another unit into a different categorical histogram Telemetry::AccumulateCategoricalKeyed( - NS_LITERAL_CSTRING("other-sample"), + "other-sample"_ns, Telemetry::LABELS_TELEMETRY_TEST_KEYED_CATEGORICAL::CommonLabel); // Get a snapshot for all the histograms @@ -281,8 +277,8 @@ TEST_F(TelemetryTestFixture, AccumulateCountHistogram_MultipleSamples) { AutoJSContextWithGlobal cx(mCleanGlobal); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in histogram Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_COUNT, samples); @@ -314,7 +310,7 @@ TEST_F(TelemetryTestFixture, AccumulateLinearHistogram_MultipleSamples) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_LINEAR"), false); + "TELEMETRY_TEST_LINEAR"_ns, false); // Accumulate in the histogram Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_LINEAR, samples); @@ -353,7 +349,7 @@ TEST_F(TelemetryTestFixture, AccumulateLinearHistogram_DifferentSamples) { mTelemetry->ClearScalars(); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_LINEAR"), false); + "TELEMETRY_TEST_LINEAR"_ns, false); // Accumulate in histogram Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_LINEAR, samples); @@ -413,11 +409,11 @@ TEST_F(TelemetryTestFixture, AccumulateKeyedCountHistogram_MultipleSamples) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_COUNT"), true); + "TELEMETRY_TEST_KEYED_COUNT"_ns, true); // Accumulate data in the provided key within the histogram - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), samples); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_COUNT, "sample"_ns, + samples); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -449,13 +445,13 @@ TEST_F(TelemetryTestFixture, TestKeyedLinearHistogram_MultipleSamples) { mTelemetry->ClearScalars(); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_LINEAR"), true); + "TELEMETRY_TEST_KEYED_LINEAR"_ns, true); const nsTArray samples({1, 5, 250000, UINT_MAX}); // Test the accumulation on the key 'testkey', using // the API that accepts histogram IDs. - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_LINEAR, - NS_LITERAL_CSTRING("testkey"), samples); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_LINEAR, "testkey"_ns, + samples); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -517,14 +513,14 @@ TEST_F(TelemetryTestFixture, TestKeyedKeysHistogram_MultipleSamples) { const nsTArray samples({false, false, true, 32, true}); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_KEYS"), true); + "TELEMETRY_TEST_KEYED_KEYS"_ns, true); // Test the accumulation on both the allowed and unallowed keys, using // the API that accepts histogram IDs. - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, - NS_LITERAL_CSTRING("not-allowed"), samples); - Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, - NS_LITERAL_CSTRING("testkey"), samples); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, "not-allowed"_ns, + samples); + Telemetry::Accumulate(Telemetry::TELEMETRY_TEST_KEYED_KEYS, "testkey"_ns, + samples); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -613,12 +609,11 @@ TEST_F(TelemetryTestFixture, TestKeyedKeysHistogram_MultipleSamples) { TEST_F(TelemetryTestFixture, AccumulateCategoricalHistogram_MultipleStringLabels) { const uint32_t kExpectedValue = 2; - const nsTArray labels( - {NS_LITERAL_CSTRING("CommonLabel"), NS_LITERAL_CSTRING("CommonLabel")}); + const nsTArray labels({"CommonLabel"_ns, "CommonLabel"_ns}); AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_CATEGORICAL"), false); + "TELEMETRY_TEST_CATEGORICAL"_ns, false); // Accumulate the units into a categorical histogram using a string label Telemetry::AccumulateCategorical(Telemetry::TELEMETRY_TEST_CATEGORICAL, @@ -658,8 +653,7 @@ TEST_F(TelemetryTestFixture, // keeping another test to check for this case alone is wasteful as we will // have to accumulate some data anyway. - const nsTArray badLabelArray( - {NS_LITERAL_CSTRING("CommonLabel"), NS_LITERAL_CSTRING("BadLabel")}); + const nsTArray badLabelArray({"CommonLabel"_ns, "BadLabel"_ns}); // Try to accumulate the array into the histogram. Telemetry::AccumulateCategorical(Telemetry::TELEMETRY_TEST_CATEGORICAL, @@ -699,7 +693,7 @@ TEST_F(TelemetryTestFixture, AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_CATEGORICAL"), false); + "TELEMETRY_TEST_CATEGORICAL"_ns, false); // Accumulate the units into a categorical histogram using the enumLabels // array @@ -747,12 +741,10 @@ TEST_F(TelemetryTestFixture, AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_CATEGORICAL"), - true); + "TELEMETRY_TEST_KEYED_CATEGORICAL"_ns, true); // Accumulate the array into the categorical keyed histogram - Telemetry::AccumulateCategoricalKeyed(NS_LITERAL_CSTRING("sampleKey"), - enumLabels); + Telemetry::AccumulateCategoricalKeyed("sampleKey"_ns, enumLabels); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); @@ -813,8 +805,8 @@ TEST_F(TelemetryTestFixture, AccumulateTimeDelta) { AutoJSContextWithGlobal cx(mCleanGlobal); - GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_COUNT"), false); + GetAndClearHistogram(cx.GetJSContext(), mTelemetry, "TELEMETRY_TEST_COUNT"_ns, + false); // Accumulate in the histogram Telemetry::AccumulateTimeDelta(Telemetry::TELEMETRY_TEST_COUNT, start - delta, @@ -857,24 +849,21 @@ TEST_F(TelemetryTestFixture, AccumulateKeyedTimeDelta) { AutoJSContextWithGlobal cx(mCleanGlobal); GetAndClearHistogram(cx.GetJSContext(), mTelemetry, - NS_LITERAL_CSTRING("TELEMETRY_TEST_KEYED_COUNT"), true); + "TELEMETRY_TEST_KEYED_COUNT"_ns, true); // Accumulate time delta in the provided key within the histogram Telemetry::AccumulateTimeDelta(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), start - delta, - start); + "sample"_ns, start - delta, start); Telemetry::AccumulateTimeDelta(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), start - delta, - start); + "sample"_ns, start - delta, start); // end > start timestamp gives zero contribution Telemetry::AccumulateTimeDelta(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), start + delta, - start); + "sample"_ns, start + delta, start); Telemetry::AccumulateTimeDelta(Telemetry::TELEMETRY_TEST_KEYED_COUNT, - NS_LITERAL_CSTRING("sample"), start, start); + "sample"_ns, start, start); // Get a snapshot for all the histograms JS::RootedValue snapshot(cx.GetJSContext()); diff --git a/toolkit/components/telemetry/tests/gtest/TestOrigins.cpp b/toolkit/components/telemetry/tests/gtest/TestOrigins.cpp index ee8d41d91b63..cb1dfb27949d 100644 --- a/toolkit/components/telemetry/tests/gtest/TestOrigins.cpp +++ b/toolkit/components/telemetry/tests/gtest/TestOrigins.cpp @@ -133,8 +133,8 @@ TEST_F(TelemetryTestFixture, RecordOriginTwiceMixed) { Preferences::SetCString("prio.publicKeyB", prioKeyB); nsTArray> encodedStrings; - GetEncodedOriginStrings( - aCx, kTelemetryTest1Metric + NS_LITERAL_CSTRING("-%u"), encodedStrings); + GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns, + encodedStrings); ASSERT_EQ(2 * TelemetryOrigin::SizeOfPrioDatasPerMetric(), encodedStrings.Length()); @@ -218,13 +218,11 @@ TEST_F(TelemetryTestFixture, EncodedSnapshot) { Preferences::SetCString("prio.publicKeyB", prioKeyB); nsTArray> firstStrings; - GetEncodedOriginStrings( - aCx, kTelemetryTest1Metric + NS_LITERAL_CSTRING("-%u"), firstStrings); + GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns, firstStrings); // Now snapshot a second time and ensure the encoded payloads change. nsTArray> secondStrings; - GetEncodedOriginStrings( - aCx, kTelemetryTest1Metric + NS_LITERAL_CSTRING("-%u"), secondStrings); + GetEncodedOriginStrings(aCx, kTelemetryTest1Metric + "-%u"_ns, secondStrings); const auto sizeOfPrioDatasPerMetric = TelemetryOrigin::SizeOfPrioDatasPerMetric(); diff --git a/toolkit/components/telemetry/tests/gtest/TestScalars.cpp b/toolkit/components/telemetry/tests/gtest/TestScalars.cpp index 3a57f8bf8028..970069b25ba1 100644 --- a/toolkit/components/telemetry/tests/gtest/TestScalars.cpp +++ b/toolkit/components/telemetry/tests/gtest/TestScalars.cpp @@ -53,7 +53,7 @@ TEST_F(TelemetryTestFixture, ScalarUnsigned) { Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_UNSIGNED_INT_KIND, false); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_UNSIGNED_INT_KIND, - NS_LITERAL_STRING("test")); + u"test"_ns); #endif // Check the recorded value. @@ -114,7 +114,7 @@ TEST_F(TelemetryTestFixture, ScalarBoolean) { 20); Telemetry::ScalarAdd(Telemetry::ScalarID::TELEMETRY_TEST_BOOLEAN_KIND, 2); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_BOOLEAN_KIND, - NS_LITERAL_STRING("test")); + u"test"_ns); #endif // Check the recorded value. @@ -163,19 +163,19 @@ TEST_F(TelemetryTestFixture, KeyedScalarUnsigned) { const uint32_t kKey1Value = 1172015; const uint32_t kKey2Value = 1172017; Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key1"), kKey1Value); + u"key1"_ns, kKey1Value); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key2"), kKey1Value); + u"key2"_ns, kKey1Value); Telemetry::ScalarAdd(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key2"), 2); + u"key2"_ns, 2); // Make sure that calls of the unsupported type don't corrupt the stored value. // Don't run this part in debug builds as that intentionally asserts. #ifndef DEBUG Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key1"), false); + u"key1"_ns, false); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("test")); + u"test"_ns); #endif // Check the recorded value. @@ -192,8 +192,8 @@ TEST_F(TelemetryTestFixture, KeyedScalarUnsigned) { // Try to use SetMaximum. const uint32_t kExpectedUintMaximum = kKey1Value * 2; Telemetry::ScalarSetMaximum( - Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key1"), kExpectedUintMaximum); + Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, u"key1"_ns, + kExpectedUintMaximum); GetScalarsSnapshot(true, cx.GetJSContext(), &scalarsSnapshot); // The first key should be different and te second is expected to be the same. @@ -211,20 +211,19 @@ TEST_F(TelemetryTestFixture, KeyedScalarBoolean) { // Set the test scalar to a known value. Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key1"), false); + u"key1"_ns, false); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key2"), true); + u"key2"_ns, true); // Make sure that calls of the unsupported type don't corrupt the stored value. // Don't run this part in debug builds as that intentionally asserts. #ifndef DEBUG Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key1"), static_cast(12)); + u"key1"_ns, static_cast(12)); Telemetry::ScalarSetMaximum( - Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key1"), 20); + Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, u"key1"_ns, 20); Telemetry::ScalarAdd(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key1"), 2); + u"key1"_ns, 2); #endif // Check the recorded value. @@ -285,7 +284,7 @@ TEST_F(TelemetryTestFixture, ScalarUnknownID) { Telemetry::ScalarID scalarId = static_cast(id); Telemetry::ScalarSet(scalarId, static_cast(1)); Telemetry::ScalarSet(scalarId, true); - Telemetry::ScalarSet(scalarId, NS_LITERAL_STRING("test")); + Telemetry::ScalarSet(scalarId, u"test"_ns); Telemetry::ScalarAdd(scalarId, 1); Telemetry::ScalarSetMaximum(scalarId, 1); @@ -296,11 +295,10 @@ TEST_F(TelemetryTestFixture, ScalarUnknownID) { << "No scalar must be recorded"; // Same for the keyed scalars. - Telemetry::ScalarSet(scalarId, NS_LITERAL_STRING("key1"), - static_cast(1)); - Telemetry::ScalarSet(scalarId, NS_LITERAL_STRING("key1"), true); - Telemetry::ScalarAdd(scalarId, NS_LITERAL_STRING("key1"), 1); - Telemetry::ScalarSetMaximum(scalarId, NS_LITERAL_STRING("key1"), 1); + Telemetry::ScalarSet(scalarId, u"key1"_ns, static_cast(1)); + Telemetry::ScalarSet(scalarId, u"key1"_ns, true); + Telemetry::ScalarAdd(scalarId, u"key1"_ns, 1); + Telemetry::ScalarSetMaximum(scalarId, u"key1"_ns, 1); // Make sure that nothing was recorded in the keyed scalars. JS::RootedValue keyedSnapshot(cx.GetJSContext()); @@ -432,16 +430,16 @@ TEST_F(TelemetryTestFixture, WrongKeyedScalarOperator) { const uint32_t kExpectedUint = 1172017; Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key1"), kExpectedUint); + u"key1"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key2"), true); + u"key2"_ns, true); TelemetryScalar::DeserializationStarted(); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_UNSIGNED_INT, - NS_LITERAL_STRING("key1"), false); + u"key1"_ns, false); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_BOOLEAN_KIND, - NS_LITERAL_STRING("key2"), static_cast(13)); + u"key2"_ns, static_cast(13)); TelemetryScalar::ApplyPendingOperations(); @@ -461,18 +459,18 @@ TEST_F(TelemetryTestFixture, TestKeyedScalarAllowedKeys) { const uint32_t kExpectedUint = 1172017; Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("only"), kExpectedUint); + u"only"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("meant"), kExpectedUint); + u"meant"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("for"), kExpectedUint); + u"for"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("testing"), kExpectedUint); + u"testing"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("invalid"), kExpectedUint); + u"invalid"_ns, kExpectedUint); Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_KEYED_WITH_KEYS, - NS_LITERAL_STRING("not-valid"), kExpectedUint); + u"not-valid"_ns, kExpectedUint); JS::RootedValue scalarsSnapshot(cx.GetJSContext()); GetScalarsSnapshot(true, cx.GetJSContext(), &scalarsSnapshot); diff --git a/toolkit/components/terminator/nsTerminator.cpp b/toolkit/components/terminator/nsTerminator.cpp index decb19a12abf..02a46c834fec 100644 --- a/toolkit/components/terminator/nsTerminator.cpp +++ b/toolkit/components/terminator/nsTerminator.cpp @@ -450,7 +450,7 @@ void nsTerminator::StartWriter() { return; } - rv = profLD->Append(NS_LITERAL_STRING("ShutdownDuration.json")); + rv = profLD->Append(u"ShutdownDuration.json"_ns); if (NS_FAILED(rv)) { return; } diff --git a/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp b/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp index 7fb046529839..c44a80c2abc6 100644 --- a/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp +++ b/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp @@ -322,7 +322,7 @@ void nsTypeAheadFind::PlayNotFoundSound() { nsCOMPtr soundURI; if (mNotFoundSoundURL.EqualsLiteral("default")) NS_NewURI(getter_AddRefs(soundURI), - NS_LITERAL_CSTRING(TYPEAHEADFIND_NOTFOUND_WAV_URL)); + nsLiteralCString(TYPEAHEADFIND_NOTFOUND_WAV_URL)); else NS_NewURI(getter_AddRefs(soundURI), mNotFoundSoundURL); @@ -882,8 +882,8 @@ void nsTypeAheadFind::RangeStartsInsideLink(nsRange* aRange, kNameSpaceID_XLink, nsGkAtoms::href); if (*aIsInsideLink) { if (!startContent->AsElement()->AttrValueIs( - kNameSpaceID_XLink, nsGkAtoms::type, - NS_LITERAL_STRING("simple"), eCaseMatters)) { + kNameSpaceID_XLink, nsGkAtoms::type, u"simple"_ns, + eCaseMatters)) { *aIsInsideLink = false; // Xlink must be type="simple" } diff --git a/toolkit/components/url-classifier/Classifier.cpp b/toolkit/components/url-classifier/Classifier.cpp index 9b1187127cc0..78c1a7a83df6 100644 --- a/toolkit/components/url-classifier/Classifier.cpp +++ b/toolkit/components/url-classifier/Classifier.cpp @@ -29,13 +29,13 @@ extern mozilla::LazyLogModule gUrlClassifierDbServiceLog; #define LOG_ENABLED() \ MOZ_LOG_TEST(gUrlClassifierDbServiceLog, mozilla::LogLevel::Debug) -#define STORE_DIRECTORY NS_LITERAL_CSTRING("safebrowsing") -#define TO_DELETE_DIR_SUFFIX NS_LITERAL_CSTRING("-to_delete") -#define BACKUP_DIR_SUFFIX NS_LITERAL_CSTRING("-backup") -#define UPDATING_DIR_SUFFIX NS_LITERAL_CSTRING("-updating") +#define STORE_DIRECTORY "safebrowsing"_ns +#define TO_DELETE_DIR_SUFFIX "-to_delete"_ns +#define BACKUP_DIR_SUFFIX "-backup"_ns +#define UPDATING_DIR_SUFFIX "-updating"_ns -#define V4_METADATA_SUFFIX NS_LITERAL_CSTRING(".metadata") -#define V2_METADATA_SUFFIX NS_LITERAL_CSTRING(".sbstore") +#define V4_METADATA_SUFFIX ".metadata"_ns +#define V2_METADATA_SUFFIX ".sbstore"_ns // The amount of time, in milliseconds, that our IO thread will stay alive after // the last event it processes. @@ -83,7 +83,7 @@ nsresult Classifier::GetPrivateStoreDirectory( const nsACString& aProvider, nsIFile** aPrivateStoreDirectory) { NS_ENSURE_ARG_POINTER(aPrivateStoreDirectory); - if (!StringEndsWith(aTableName, NS_LITERAL_CSTRING("-proto"))) { + if (!StringEndsWith(aTableName, "-proto"_ns)) { // Only V4 table names (ends with '-proto') would be stored // to per-provider sub-directory. nsCOMPtr(aRootStoreDirectory).forget(aPrivateStoreDirectory); @@ -137,9 +137,9 @@ Classifier::Classifier() mUpdateInterrupted(true), mIsClosed(false) { // Make a lazy thread for any IO - mUpdateThread = new LazyIdleThread( - DEFAULT_THREAD_TIMEOUT_MS, NS_LITERAL_CSTRING("Classifier Update"), - LazyIdleThread::ShutdownMethod::ManualShutdown); + mUpdateThread = + new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, "Classifier Update"_ns, + LazyIdleThread::ShutdownMethod::ManualShutdown); } Classifier::~Classifier() { @@ -224,13 +224,10 @@ nsresult Classifier::ClearLegacyFiles() { } nsTArray tables = { - NS_LITERAL_CSTRING("test-phish-simple"), - NS_LITERAL_CSTRING("test-malware-simple"), - NS_LITERAL_CSTRING("test-unwanted-simple"), - NS_LITERAL_CSTRING("test-harmful-simple"), - NS_LITERAL_CSTRING("test-track-simple"), - NS_LITERAL_CSTRING("test-trackwhite-simple"), - NS_LITERAL_CSTRING("test-block-simple"), + "test-phish-simple"_ns, "test-malware-simple"_ns, + "test-unwanted-simple"_ns, "test-harmful-simple"_ns, + "test-track-simple"_ns, "test-trackwhite-simple"_ns, + "test-block-simple"_ns, }; const auto fnFindAndRemove = [](nsIFile* aRootDirectory, @@ -262,10 +259,8 @@ nsresult Classifier::ClearLegacyFiles() { for (const auto& table : tables) { // Remove both .sbstore and .vlpse if .sbstore exists - if (fnFindAndRemove(mRootStoreDirectory, - table + NS_LITERAL_CSTRING(".sbstore"))) { - fnFindAndRemove(mRootStoreDirectory, - table + NS_LITERAL_CSTRING(".vlpset")); + if (fnFindAndRemove(mRootStoreDirectory, table + ".sbstore"_ns)) { + fnFindAndRemove(mRootStoreDirectory, table + ".vlpset"_ns); } } @@ -952,8 +947,7 @@ nsresult Classifier::RegenActiveTables() { // The extension of V2 and V4 prefix files is .vlpset // We still check .pset here for legacy load. - nsTArray exts = {NS_LITERAL_CSTRING(".vlpset"), - NS_LITERAL_CSTRING(".pset")}; + nsTArray exts = {".vlpset"_ns, ".pset"_ns}; nsTArray foundTables; nsresult rv = ScanStoreDir(mRootStoreDirectory, exts, foundTables); Unused << NS_WARN_IF(NS_FAILED(rv)); @@ -986,13 +980,10 @@ nsresult Classifier::RegenActiveTables() { nsresult Classifier::AddMozEntries(nsTArray& aTables) { nsTArray tables = { - NS_LITERAL_CSTRING("moztest-phish-simple"), - NS_LITERAL_CSTRING("moztest-malware-simple"), - NS_LITERAL_CSTRING("moztest-unwanted-simple"), - NS_LITERAL_CSTRING("moztest-harmful-simple"), - NS_LITERAL_CSTRING("moztest-track-simple"), - NS_LITERAL_CSTRING("moztest-trackwhite-simple"), - NS_LITERAL_CSTRING("moztest-block-simple"), + "moztest-phish-simple"_ns, "moztest-malware-simple"_ns, + "moztest-unwanted-simple"_ns, "moztest-harmful-simple"_ns, + "moztest-track-simple"_ns, "moztest-trackwhite-simple"_ns, + "moztest-block-simple"_ns, }; for (const auto& table : tables) { @@ -1576,7 +1567,7 @@ RefPtr Classifier::GetLookupCache(const nsACString& aTable, } } - if (StringEndsWith(aTable, NS_LITERAL_CSTRING("-proto"))) { + if (StringEndsWith(aTable, "-proto"_ns)) { cache = new LookupCacheV4(aTable, provider, rootStoreDirectory); } else { cache = new LookupCacheV2(aTable, provider, rootStoreDirectory); diff --git a/toolkit/components/url-classifier/HashStore.cpp b/toolkit/components/url-classifier/HashStore.cpp index 3229b0bebb98..2b88fddda2ac 100644 --- a/toolkit/components/url-classifier/HashStore.cpp +++ b/toolkit/components/url-classifier/HashStore.cpp @@ -252,7 +252,7 @@ nsresult HashStore::Reset() { nsresult rv = mStoreDirectory->Clone(getter_AddRefs(storeFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = storeFile->AppendNative(mTableName + NS_LITERAL_CSTRING(STORE_SUFFIX)); + rv = storeFile->AppendNative(mTableName + nsLiteralCString(STORE_SUFFIX)); NS_ENSURE_SUCCESS(rv, rv); rv = storeFile->Remove(false); @@ -304,7 +304,7 @@ nsresult HashStore::Open(uint32_t aVersion) { nsresult rv = mStoreDirectory->Clone(getter_AddRefs(storeFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = storeFile->AppendNative(mTableName + NS_LITERAL_CSTRING(".sbstore")); + rv = storeFile->AppendNative(mTableName + ".sbstore"_ns); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr origStream; @@ -913,7 +913,7 @@ nsresult HashStore::WriteFile() { nsCOMPtr storeFile; nsresult rv = mStoreDirectory->Clone(getter_AddRefs(storeFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = storeFile->AppendNative(mTableName + NS_LITERAL_CSTRING(".sbstore")); + rv = storeFile->AppendNative(mTableName + ".sbstore"_ns); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr out; @@ -962,7 +962,7 @@ nsresult HashStore::ReadCompletionsLegacyV3(AddCompleteArray& aCompletes) { nsresult rv = mStoreDirectory->Clone(getter_AddRefs(storeFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = storeFile->AppendNative(mTableName + NS_LITERAL_CSTRING(STORE_SUFFIX)); + rv = storeFile->AppendNative(mTableName + nsLiteralCString(STORE_SUFFIX)); NS_ENSURE_SUCCESS(rv, rv); uint32_t offset = mFileSize - diff --git a/toolkit/components/url-classifier/LookupCache.cpp b/toolkit/components/url-classifier/LookupCache.cpp index d0b03054f101..b85df17532fb 100644 --- a/toolkit/components/url-classifier/LookupCache.cpp +++ b/toolkit/components/url-classifier/LookupCache.cpp @@ -435,7 +435,7 @@ nsresult LookupCache::GetLookupWhitelistFragments( // Fallback to use default fragment rule when the URL doesn't contain // "/?resoruce=" because this means the URL is not generated in // CreatePairwiseWhiteListURI() - if (!FindInReadable(NS_LITERAL_CSTRING("/?resource="), iter, iter_end)) { + if (!FindInReadable("/?resource="_ns, iter, iter_end)) { return GetLookupFragments(aSpec, aFragments); } @@ -453,7 +453,7 @@ nsresult LookupCache::GetLookupWhitelistFragments( topLevelURL.BeginReading(begin); topLevelURL.EndReading(end); int numTopLevelURLComponents = 0; - while (RFindInReadable(NS_LITERAL_CSTRING("."), begin, end) && + while (RFindInReadable("."_ns, begin, end) && numTopLevelURLComponents < MAX_HOST_COMPONENTS) { // don't bother checking toplevel domains if (++numTopLevelURLComponents >= 2) { @@ -540,7 +540,7 @@ nsresult LookupCache::GetLookupFragments(const nsACString& aSpec, host.BeginReading(begin); host.EndReading(end); int numHostComponents = 0; - while (RFindInReadable(NS_LITERAL_CSTRING("."), begin, end) && + while (RFindInReadable("."_ns, begin, end) && numHostComponents < MAX_HOST_COMPONENTS) { // don't bother checking toplevel domains if (++numHostComponents >= 2) { @@ -999,7 +999,7 @@ nsresult LookupCacheV2::ClearLegacyFile() { return rv; } - rv = file->AppendNative(mTableName + NS_LITERAL_CSTRING(".pset")); + rv = file->AppendNative(mTableName + ".pset"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1022,9 +1022,7 @@ nsresult LookupCacheV2::ClearLegacyFile() { return NS_OK; } -nsCString LookupCacheV2::GetPrefixSetSuffix() const { - return NS_LITERAL_CSTRING(".vlpset"); -} +nsCString LookupCacheV2::GetPrefixSetSuffix() const { return ".vlpset"_ns; } // Support creating built-in entries for phsihing, malware, unwanted, harmful, // tracking/tracking whitelist and flash block tables. @@ -1039,32 +1037,26 @@ nsresult LookupCacheV2::LoadMozEntries() { if (mTableName.EqualsLiteral("moztest-phish-simple")) { // Entries for phishing table - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/firefox/its-a-trap.html")); + entries.AppendElement("itisatrap.org/firefox/its-a-trap.html"_ns); } else if (mTableName.EqualsLiteral("moztest-malware-simple")) { // Entries for malware table - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/firefox/its-an-attack.html")); + entries.AppendElement("itisatrap.org/firefox/its-an-attack.html"_ns); } else if (mTableName.EqualsLiteral("moztest-unwanted-simple")) { // Entries for unwanted table - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/firefox/unwanted.html")); + entries.AppendElement("itisatrap.org/firefox/unwanted.html"_ns); } else if (mTableName.EqualsLiteral("moztest-harmful-simple")) { // Entries for harmfule tables - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/firefox/harmful.html")); + entries.AppendElement("itisatrap.org/firefox/harmful.html"_ns); } else if (mTableName.EqualsLiteral("moztest-track-simple")) { // Entries for tracking table - entries.AppendElement(NS_LITERAL_CSTRING("trackertest.org/")); - entries.AppendElement(NS_LITERAL_CSTRING("itisatracker.org/")); + entries.AppendElement("trackertest.org/"_ns); + entries.AppendElement("itisatracker.org/"_ns); } else if (mTableName.EqualsLiteral("moztest-trackwhite-simple")) { // Entries for tracking whitelist table - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/?resource=itisatracker.org")); + entries.AppendElement("itisatrap.org/?resource=itisatracker.org"_ns); } else if (mTableName.EqualsLiteral("moztest-block-simple")) { // Entries for flash block table - entries.AppendElement( - NS_LITERAL_CSTRING("itisatrap.org/firefox/blocked.html")); + entries.AppendElement("itisatrap.org/firefox/blocked.html"_ns); } else { MOZ_ASSERT_UNREACHABLE(); } diff --git a/toolkit/components/url-classifier/LookupCacheV4.cpp b/toolkit/components/url-classifier/LookupCacheV4.cpp index 99a532da1657..c78e5369d7a4 100644 --- a/toolkit/components/url-classifier/LookupCacheV4.cpp +++ b/toolkit/components/url-classifier/LookupCacheV4.cpp @@ -17,7 +17,7 @@ extern mozilla::LazyLogModule gUrlClassifierDbServiceLog; #define LOG_ENABLED() \ MOZ_LOG_TEST(gUrlClassifierDbServiceLog, mozilla::LogLevel::Debug) -#define METADATA_SUFFIX NS_LITERAL_CSTRING(".metadata") +#define METADATA_SUFFIX ".metadata"_ns namespace mozilla { namespace safebrowsing { @@ -162,7 +162,7 @@ nsresult LookupCacheV4::ClearLegacyFile() { return rv; } - rv = file->AppendNative(mTableName + NS_LITERAL_CSTRING(".pset")); + rv = file->AppendNative(mTableName + ".pset"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -192,7 +192,7 @@ nsresult LookupCacheV4::LoadLegacyFile() { return rv; } - rv = file->AppendNative(mTableName + NS_LITERAL_CSTRING(".pset")); + rv = file->AppendNative(mTableName + ".pset"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -264,9 +264,7 @@ nsresult LookupCacheV4::SanityCheck(const Header& aHeader) { return NS_OK; } -nsCString LookupCacheV4::GetPrefixSetSuffix() const { - return NS_LITERAL_CSTRING(".vlpset"); -} +nsCString LookupCacheV4::GetPrefixSetSuffix() const { return ".vlpset"_ns; } static nsresult AppendPrefixToMap(PrefixStringMap& prefixes, const nsACString& prefix) { diff --git a/toolkit/components/url-classifier/ProtocolParser.cpp b/toolkit/components/url-classifier/ProtocolParser.cpp index 55ac2692257d..5bfccc8999f5 100644 --- a/toolkit/components/url-classifier/ProtocolParser.cpp +++ b/toolkit/components/url-classifier/ProtocolParser.cpp @@ -166,10 +166,10 @@ nsresult ProtocolParserV2::ProcessControl(bool* aDone) { while (NextLine(line)) { PARSER_LOG(("Processing %s\n", line.get())); - if (StringBeginsWith(line, NS_LITERAL_CSTRING("i:"))) { + if (StringBeginsWith(line, "i:"_ns)) { // Set the table name from the table header line. SetCurrentTable(Substring(line, 2)); - } else if (StringBeginsWith(line, NS_LITERAL_CSTRING("n:"))) { + } else if (StringBeginsWith(line, "n:"_ns)) { if (PR_sscanf(line.get(), "n:%d", &mUpdateWaitSec) != 1) { PARSER_LOG(("Error parsing n: '%s' (%d)", line.get(), mUpdateWaitSec)); return NS_ERROR_FAILURE; @@ -177,17 +177,17 @@ nsresult ProtocolParserV2::ProcessControl(bool* aDone) { } else if (line.EqualsLiteral("r:pleasereset")) { PARSER_LOG(("All tables will be reset.")); mTablesToReset = mRequestedTables.Clone(); - } else if (StringBeginsWith(line, NS_LITERAL_CSTRING("u:"))) { + } else if (StringBeginsWith(line, "u:"_ns)) { rv = ProcessForward(line); NS_ENSURE_SUCCESS(rv, rv); - } else if (StringBeginsWith(line, NS_LITERAL_CSTRING("a:")) || - StringBeginsWith(line, NS_LITERAL_CSTRING("s:"))) { + } else if (StringBeginsWith(line, "a:"_ns) || + StringBeginsWith(line, "s:"_ns)) { rv = ProcessChunkControl(line); NS_ENSURE_SUCCESS(rv, rv); *aDone = false; return NS_OK; - } else if (StringBeginsWith(line, NS_LITERAL_CSTRING("ad:")) || - StringBeginsWith(line, NS_LITERAL_CSTRING("sd:"))) { + } else if (StringBeginsWith(line, "ad:"_ns) || + StringBeginsWith(line, "sd:"_ns)) { rv = ProcessExpirations(line); NS_ENSURE_SUCCESS(rv, rv); } @@ -259,14 +259,11 @@ nsresult ProtocolParserV2::ProcessChunkControl(const nsCString& aLine) { return NS_ERROR_FAILURE; } - if (StringEndsWith(mTableUpdate->TableName(), - NS_LITERAL_CSTRING("-shavar")) || - StringEndsWith(mTableUpdate->TableName(), - NS_LITERAL_CSTRING("-simple"))) { + if (StringEndsWith(mTableUpdate->TableName(), "-shavar"_ns) || + StringEndsWith(mTableUpdate->TableName(), "-simple"_ns)) { // Accommodate test tables ending in -simple for now. mChunkState.type = (command == 'a') ? CHUNK_ADD : CHUNK_SUB; - } else if (StringEndsWith(mTableUpdate->TableName(), - NS_LITERAL_CSTRING("-digest256"))) { + } else if (StringEndsWith(mTableUpdate->TableName(), "-digest256"_ns)) { mChunkState.type = (command == 'a') ? CHUNK_ADD_DIGEST : CHUNK_SUB_DIGEST; } nsresult rv; @@ -339,12 +336,10 @@ nsresult ProtocolParserV2::ProcessChunk(bool* aDone) { *aDone = false; mState = PROTOCOL_STATE_CONTROL; - if (StringEndsWith(mTableUpdate->TableName(), - NS_LITERAL_CSTRING("-shavar"))) { + if (StringEndsWith(mTableUpdate->TableName(), "-shavar"_ns)) { return ProcessShaChunk(chunk); } - if (StringEndsWith(mTableUpdate->TableName(), - NS_LITERAL_CSTRING("-digest256"))) { + if (StringEndsWith(mTableUpdate->TableName(), "-digest256"_ns)) { return ProcessDigestChunk(chunk); } return ProcessPlaintextChunk(chunk); diff --git a/toolkit/components/url-classifier/VariableLengthPrefixSet.cpp b/toolkit/components/url-classifier/VariableLengthPrefixSet.cpp index e3ff1ab537db..57efacd0bca0 100644 --- a/toolkit/components/url-classifier/VariableLengthPrefixSet.cpp +++ b/toolkit/components/url-classifier/VariableLengthPrefixSet.cpp @@ -459,8 +459,8 @@ VariableLengthPrefixSet::CollectReports(nsIHandleReportCallback* aHandleReport, return aHandleReport->Callback( EmptyCString(), mMemoryReportPath, KIND_HEAP, UNITS_BYTES, amount, - NS_LITERAL_CSTRING("Memory used by the variable-length prefix set for a " - "URL classifier."), + nsLiteralCString("Memory used by the variable-length prefix set for a " + "URL classifier."), aData); } diff --git a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp index dcd8b7aa6a7e..497cbfa8b2ea 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp @@ -68,22 +68,22 @@ nsresult TablesToResponse(const nsACString& tables) { // We don't check mCheckMalware and friends because disabled tables are // never included - if (FindInReadable(NS_LITERAL_CSTRING("-malware-"), tables)) { + if (FindInReadable("-malware-"_ns, tables)) { return NS_ERROR_MALWARE_URI; } - if (FindInReadable(NS_LITERAL_CSTRING("-harmful-"), tables)) { + if (FindInReadable("-harmful-"_ns, tables)) { return NS_ERROR_HARMFUL_URI; } - if (FindInReadable(NS_LITERAL_CSTRING("-phish-"), tables)) { + if (FindInReadable("-phish-"_ns, tables)) { return NS_ERROR_PHISHING_URI; } - if (FindInReadable(NS_LITERAL_CSTRING("-unwanted-"), tables)) { + if (FindInReadable("-unwanted-"_ns, tables)) { return NS_ERROR_UNWANTED_URI; } - if (FindInReadable(NS_LITERAL_CSTRING("-track-"), tables)) { + if (FindInReadable("-track-"_ns, tables)) { return NS_ERROR_TRACKING_URI; } - if (FindInReadable(NS_LITERAL_CSTRING("-block-"), tables)) { + if (FindInReadable("-block-"_ns, tables)) { return NS_ERROR_BLOCKED_URI; } return NS_OK; @@ -570,8 +570,7 @@ nsUrlClassifierDBServiceWorker::BeginStream(const nsACString& table) { // Check if we should use protobuf to parse the update. bool useProtobuf = false; for (size_t i = 0; i < mUpdateTables.Length(); i++) { - bool isCurProtobuf = - StringEndsWith(mUpdateTables[i], NS_LITERAL_CSTRING("-proto")); + bool isCurProtobuf = StringEndsWith(mUpdateTables[i], "-proto"_ns); if (0 == i) { // Use the first table name to decice if all the subsequent tables @@ -1286,7 +1285,7 @@ nsUrlClassifierLookupCallback::CompletionV2(const nsACString& aCompleteHash, LOG(("nsUrlClassifierLookupCallback::Completion [%p, %s, %d]", this, PromiseFlatCString(aTableName).get(), aChunkId)); - MOZ_ASSERT(!StringEndsWith(aTableName, NS_LITERAL_CSTRING("-proto"))); + MOZ_ASSERT(!StringEndsWith(aTableName, "-proto"_ns)); RefPtr result = new CacheResultV2(); @@ -1306,7 +1305,7 @@ nsUrlClassifierLookupCallback::CompletionV4(const nsACString& aPartialHash, LOG(("nsUrlClassifierLookupCallback::CompletionV4 [%p, %s, %d]", this, PromiseFlatCString(aTableName).get(), aNegativeCacheDuration)); - MOZ_ASSERT(StringEndsWith(aTableName, NS_LITERAL_CSTRING("-proto"))); + MOZ_ASSERT(StringEndsWith(aTableName, "-proto"_ns)); if (!aFullHashes) { return NS_ERROR_INVALID_ARG; @@ -1374,7 +1373,7 @@ nsresult nsUrlClassifierLookupCallback::HandleResults() { // No results, this URI is clean. LOG(("nsUrlClassifierLookupCallback::HandleResults [%p, no results]", this)); - return mCallback->HandleEvent(NS_LITERAL_CSTRING("")); + return mCallback->HandleEvent(""_ns); } MOZ_ASSERT(mPendingCompletions == 0, "HandleResults() should never be " @@ -1466,9 +1465,9 @@ struct Provider { // Order matters // Provider which is not included in this table has the lowest priority 0 static const Provider kBuiltInProviders[] = { - {NS_LITERAL_CSTRING("mozilla"), 1}, - {NS_LITERAL_CSTRING("google4"), 2}, - {NS_LITERAL_CSTRING("google"), 3}, + {"mozilla"_ns, 1}, + {"google4"_ns, 2}, + {"google"_ns, 3}, }; // ------------------------------------------------------------------------- @@ -1739,7 +1738,7 @@ nsUrlClassifierDBService::Classify(nsIPrincipal* aPrincipal, uint32_t perm; nsresult rv = permissionManager->TestPermissionFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("safe-browsing"), &perm); + aPrincipal, "safe-browsing"_ns, &perm); NS_ENSURE_SUCCESS(rv, rv); if (perm == nsIPermissionManager::ALLOW_ACTION) { @@ -1937,7 +1936,7 @@ nsUrlClassifierDBService::SendThreatHitReport(nsIChannel* aChannel, formatter->FormatURLPref(NS_ConvertUTF8toUTF16(reportUrlPref), urlStr); NS_ENSURE_SUCCESS(rv, rv); - if (urlStr.IsEmpty() || NS_LITERAL_STRING("about:blank").Equals(urlStr)) { + if (urlStr.IsEmpty() || u"about:blank"_ns.Equals(urlStr)) { LOG(("%s is missing a ThreatHit data reporting URL.", PromiseFlatCString(aProvider).get())); return NS_OK; @@ -1987,17 +1986,15 @@ nsUrlClassifierDBService::SendThreatHitReport(nsIChannel* aChannel, nsCOMPtr uploadChannel(do_QueryInterface(reportChannel)); NS_ENSURE_TRUE(uploadChannel, NS_ERROR_FAILURE); - rv = uploadChannel->SetUploadStream( - sis, NS_LITERAL_CSTRING("application/x-protobuf"), -1); + rv = uploadChannel->SetUploadStream(sis, "application/x-protobuf"_ns, -1); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr httpChannel(do_QueryInterface(reportChannel)); NS_ENSURE_TRUE(httpChannel, NS_ERROR_FAILURE); - rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChannel->SetRequestMethod("POST"_ns); NS_ENSURE_SUCCESS(rv, rv); // Disable keepalive. - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Connection"), - NS_LITERAL_CSTRING("close"), false); + rv = httpChannel->SetRequestHeader("Connection"_ns, "close"_ns, false); NS_ENSURE_SUCCESS(rv, rv); RefPtr listener = new ThreatHitReportListener(); @@ -2024,9 +2021,8 @@ nsUrlClassifierDBService::Lookup(nsIPrincipal* aPrincipal, Classifier::SplitTables(aTables, tableArray); nsCOMPtr feature; - nsresult rv = - CreateFeatureWithTables(NS_LITERAL_CSTRING("lookup"), tableArray, - nsTArray(), getter_AddRefs(feature)); + nsresult rv = CreateFeatureWithTables( + "lookup"_ns, tableArray, nsTArray(), getter_AddRefs(feature)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr uri; diff --git a/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp b/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp index b5c0a88d2957..7192db56c274 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp @@ -162,9 +162,8 @@ nsresult nsUrlClassifierStreamUpdater::FetchUpdate( nsCOMPtr httpChannel = do_QueryInterface(mChannel, &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = httpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("X-HTTP-Method-Override"), - NS_LITERAL_CSTRING("POST"), false); + rv = httpChannel->SetRequestHeader("X-HTTP-Method-Override"_ns, "POST"_ns, + false); NS_ENSURE_SUCCESS(rv, rv); } else if (!aRequestPayload.IsEmpty()) { rv = AddRequestBody(aRequestPayload); @@ -175,16 +174,14 @@ nsresult nsUrlClassifierStreamUpdater::FetchUpdate( // purposes. // This is only used for testing and should be deleted. if (aUpdateUrl->SchemeIs("file") || aUpdateUrl->SchemeIs("data")) { - mChannel->SetContentType( - NS_LITERAL_CSTRING("application/vnd.google.safebrowsing-update")); + mChannel->SetContentType("application/vnd.google.safebrowsing-update"_ns); } else { // We assume everything else is an HTTP request. // Disable keepalive. nsCOMPtr httpChannel = do_QueryInterface(mChannel, &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("Connection"), - NS_LITERAL_CSTRING("close"), false); + rv = httpChannel->SetRequestHeader("Connection"_ns, "close"_ns, false); NS_ENSURE_SUCCESS(rv, rv); } @@ -355,17 +352,17 @@ nsUrlClassifierStreamUpdater::UpdateUrlRequested(const nsACString& aUrl, } // Allow data: and file: urls for unit testing purposes, otherwise assume http - if (StringBeginsWith(aUrl, NS_LITERAL_CSTRING("data:")) || - StringBeginsWith(aUrl, NS_LITERAL_CSTRING("file:"))) { + if (StringBeginsWith(aUrl, "data:"_ns) || + StringBeginsWith(aUrl, "file:"_ns)) { update->mUrl = aUrl; } else { // For unittesting update urls to localhost should use http, not https // (otherwise the connection will fail silently, since there will be no // cert available). - if (!StringBeginsWith(aUrl, NS_LITERAL_CSTRING("localhost"))) { - update->mUrl = NS_LITERAL_CSTRING("https://") + aUrl; + if (!StringBeginsWith(aUrl, "localhost"_ns)) { + update->mUrl = "https://"_ns + aUrl; } else { - update->mUrl = NS_LITERAL_CSTRING("http://") + aUrl; + update->mUrl = "http://"_ns + aUrl; } } update->mTable = aTable; @@ -543,14 +540,13 @@ nsresult nsUrlClassifierStreamUpdater::AddRequestBody( nsCOMPtr uploadChannel = do_QueryInterface(mChannel, &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = uploadChannel->SetUploadStream(strStream, - NS_LITERAL_CSTRING("text/plain"), -1); + rv = uploadChannel->SetUploadStream(strStream, "text/plain"_ns, -1); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr httpChannel = do_QueryInterface(mChannel, &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = httpChannel->SetRequestMethod(NS_LITERAL_CSTRING("POST")); + rv = httpChannel->SetRequestMethod("POST"_ns); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; diff --git a/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp b/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp index 44585a4c4fd8..9719b771bf7e 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierUtils.cpp @@ -349,7 +349,7 @@ nsUrlClassifierUtils::GetProvider(const nsACString& aTableName, nsCString* provider = nullptr; if (IsTestTable(aTableName)) { - aProvider = NS_LITERAL_CSTRING(TESTING_TABLE_PROVIDER_NAME); + aProvider = nsLiteralCString(TESTING_TABLE_PROVIDER_NAME); } else if (mProviderDict.Get(aTableName, &provider)) { aProvider = provider ? *provider : EmptyCString(); } else { @@ -364,13 +364,10 @@ nsUrlClassifierUtils::GetTelemetryProvider(const nsACString& aTableName, GetProvider(aTableName, aProvider); // Whitelist known providers to avoid reporting on private ones. // An empty provider is treated as "other" - if (!NS_LITERAL_CSTRING("mozilla").Equals(aProvider) && - !NS_LITERAL_CSTRING("google").Equals(aProvider) && - !NS_LITERAL_CSTRING("google4").Equals(aProvider) && - !NS_LITERAL_CSTRING("baidu").Equals(aProvider) && - !NS_LITERAL_CSTRING("mozcn").Equals(aProvider) && - !NS_LITERAL_CSTRING("yandex").Equals(aProvider) && - !NS_LITERAL_CSTRING(TESTING_TABLE_PROVIDER_NAME).Equals(aProvider)) { + if (!"mozilla"_ns.Equals(aProvider) && !"google"_ns.Equals(aProvider) && + !"google4"_ns.Equals(aProvider) && !"baidu"_ns.Equals(aProvider) && + !"mozcn"_ns.Equals(aProvider) && !"yandex"_ns.Equals(aProvider) && + !nsLiteralCString(TESTING_TABLE_PROVIDER_NAME).Equals(aProvider)) { aProvider.AssignLiteral("other"); } @@ -1047,7 +1044,7 @@ void nsUrlClassifierUtils::CanonicalNum(const nsACString& num, uint32_t bytes, if (_retval.IsEmpty()) { _retval.Assign(buf); } else { - _retval = nsDependentCString(buf) + NS_LITERAL_CSTRING(".") + _retval; + _retval = nsDependentCString(buf) + "."_ns + _retval; } val >>= 8; } @@ -1091,15 +1088,14 @@ bool nsUrlClassifierUtils::ShouldURLEscape(const unsigned char c) const { // url entries in it. moztest tables don't support updates. // static bool nsUrlClassifierUtils::IsMozTestTable(const nsACString& aTableName) { - return StringBeginsWith(aTableName, NS_LITERAL_CSTRING("moztest-")); + return StringBeginsWith(aTableName, "moztest-"_ns); } // test- tables are used by testcases and can add custom test entries // through update API. // static bool nsUrlClassifierUtils::IsTestTable(const nsACString& aTableName) { - return IsMozTestTable(aTableName) || - StringBeginsWith(aTableName, NS_LITERAL_CSTRING("test")); + return IsMozTestTable(aTableName) || StringBeginsWith(aTableName, "test"_ns); } bool nsUrlClassifierUtils::IsInSafeMode() { diff --git a/toolkit/components/url-classifier/tests/gtest/Common.cpp b/toolkit/components/url-classifier/tests/gtest/Common.cpp index b07f35344046..00e375e2598d 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.cpp +++ b/toolkit/components/url-classifier/tests/gtest/Common.cpp @@ -19,7 +19,7 @@ using namespace mozilla; using namespace mozilla::safebrowsing; -#define GTEST_SAFEBROWSING_DIR NS_LITERAL_CSTRING("safebrowsing") +#define GTEST_SAFEBROWSING_DIR "safebrowsing"_ns template void RunTestInNewThread(Function&& aFunction) { diff --git a/toolkit/components/url-classifier/tests/gtest/Common.h b/toolkit/components/url-classifier/tests/gtest/Common.h index 2f5591c1da72..97b81144c36e 100644 --- a/toolkit/components/url-classifier/tests/gtest/Common.h +++ b/toolkit/components/url-classifier/tests/gtest/Common.h @@ -22,8 +22,8 @@ class TableUpdate; } // namespace safebrowsing } // namespace mozilla -#define GTEST_TABLE_V4 NS_LITERAL_CSTRING("gtest-malware-proto") -#define GTEST_TABLE_V2 NS_LITERAL_CSTRING("gtest-malware-simple") +#define GTEST_TABLE_V4 "gtest-malware-proto"_ns +#define GTEST_TABLE_V2 "gtest-malware-simple"_ns template void RunTestInNewThread(Function&& aFunction); diff --git a/toolkit/components/url-classifier/tests/gtest/TestCaching.cpp b/toolkit/components/url-classifier/tests/gtest/TestCaching.cpp index 159f76d49840..48d96eb9fd3d 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestCaching.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestCaching.cpp @@ -8,10 +8,10 @@ #define EXPIRED_TIME_SEC (PR_Now() / PR_USEC_PER_SEC - 3600) #define NOTEXPIRED_TIME_SEC (PR_Now() / PR_USEC_PER_SEC + 3600) -#define CACHED_URL NS_LITERAL_CSTRING("cache.com/") -#define NEG_CACHE_EXPIRED_URL NS_LITERAL_CSTRING("cache.negExpired.com/") -#define POS_CACHE_EXPIRED_URL NS_LITERAL_CSTRING("cache.posExpired.com/") -#define BOTH_CACHE_EXPIRED_URL NS_LITERAL_CSTRING("cache.negAndposExpired.com/") +#define CACHED_URL "cache.com/"_ns +#define NEG_CACHE_EXPIRED_URL "cache.negExpired.com/"_ns +#define POS_CACHE_EXPIRED_URL "cache.posExpired.com/"_ns +#define BOTH_CACHE_EXPIRED_URL "cache.negAndposExpired.com/"_ns static void SetupCacheEntry(LookupCacheV2* aLookupCache, const nsCString& aCompletion, @@ -76,9 +76,8 @@ static void TestCache(const Completion aCompletion, bool aExpectedHas, RefPtr cache = SetupLookupCache(array); // Create an expired entry and a non-expired entry - SetupCacheEntry(cache, NS_LITERAL_CSTRING("cache.notexpired.com/")); - SetupCacheEntry(cache, NS_LITERAL_CSTRING("cache.expired.com/"), true, - true); + SetupCacheEntry(cache, "cache.notexpired.com/"_ns); + SetupCacheEntry(cache, "cache.expired.com/"_ns, true, true); cache->Has(aCompletion, &has, &matchLength, &confirmed); inCache = cache->IsInCache(aCompletion.ToUint32()); @@ -104,40 +103,32 @@ static void TestCache(const nsCString& aURL, bool aExpectedHas, // any prefix in the local database. TEST(UrlClassifierCaching, NotFound) { - TestCache(NS_LITERAL_CSTRING("nomatch.com/"), false, false, - false); - TestCache(NS_LITERAL_CSTRING("nomatch.com/"), false, false, - false); + TestCache("nomatch.com/"_ns, false, false, false); + TestCache("nomatch.com/"_ns, false, false, false); } // This testcase check the returned result of |Has| API if fullhash find a match // in the local database but not in the cache. TEST(UrlClassifierCaching, NotInCache) { - TestCache(NS_LITERAL_CSTRING("gound.com/"), true, false, - false); - TestCache(NS_LITERAL_CSTRING("gound.com/"), true, false, - false); + TestCache("gound.com/"_ns, true, false, false); + TestCache("gound.com/"_ns, true, false, false); } // This testcase check the returned result of |Has| API if fullhash matches // a cache entry in positive cache. TEST(UrlClassifierCaching, InPositiveCacheNotExpired) { - TestCache(NS_LITERAL_CSTRING("cache.notexpired.com/"), true, - true, true); - TestCache(NS_LITERAL_CSTRING("cache.notexpired.com/"), true, - true, true); + TestCache("cache.notexpired.com/"_ns, true, true, true); + TestCache("cache.notexpired.com/"_ns, true, true, true); } // This testcase check the returned result of |Has| API if fullhash matches // a cache entry in positive cache but that it is expired. TEST(UrlClassifierCaching, InPositiveCacheExpired) { - TestCache(NS_LITERAL_CSTRING("cache.expired.com/"), true, - false, true); - TestCache(NS_LITERAL_CSTRING("cache.expired.com/"), true, - false, true); + TestCache("cache.expired.com/"_ns, true, false, true); + TestCache("cache.expired.com/"_ns, true, false, true); } // This testcase check the returned result of |Has| API if fullhash matches @@ -148,10 +139,10 @@ TEST(UrlClassifierCaching, InNegativeCacheNotExpired) // but completion doesn't match any fullhash in positive cache. Completion prefix; - prefix.FromPlaintext(NS_LITERAL_CSTRING("cache.notexpired.com/")); + prefix.FromPlaintext("cache.notexpired.com/"_ns); Completion fullhash; - fullhash.FromPlaintext(NS_LITERAL_CSTRING("firefox.com/")); + fullhash.FromPlaintext("firefox.com/"_ns); // Overwrite the 4-byte prefix of `fullhash` so that it conflicts with // `prefix`. Since "cache.notexpired.com" is added to database in TestCache as @@ -170,10 +161,10 @@ TEST(UrlClassifierCaching, InNegativeCacheExpired) // Create a fullhash whose prefix is in the cache. Completion prefix; - prefix.FromPlaintext(NS_LITERAL_CSTRING("cache.expired.com/")); + prefix.FromPlaintext("cache.expired.com/"_ns); Completion fullhash; - fullhash.FromPlaintext(NS_LITERAL_CSTRING("firefox.com/")); + fullhash.FromPlaintext("firefox.com/"_ns); memcpy(fullhash.buf, prefix.buf, 10); diff --git a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp b/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp index 58698aea3f48..6835103b3036 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestChunkSet.cpp @@ -275,7 +275,7 @@ TEST(UrlClassifierChunkSet, Serialize) printf("mergeResult: %s\n", mergeResult.get()); - nsAutoCString expected(NS_LITERAL_CSTRING("1-10,12-14,16,20")); + nsAutoCString expected("1-10,12-14,16,20"_ns); ASSERT_TRUE(mergeResult.Equals(expected)); } diff --git a/toolkit/components/url-classifier/tests/gtest/TestClassifier.cpp b/toolkit/components/url-classifier/tests/gtest/TestClassifier.cpp index ad9f717d3653..4000d6b32ed4 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestClassifier.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestClassifier.cpp @@ -56,8 +56,7 @@ TEST(UrlClassifierClassifier, ReadNoiseEntriesV4) ASSERT_TRUE(rv == NS_OK) << "Fail to build LookupCache"; - TestReadNoiseEntries(classifier, GTEST_TABLE_V4, - NS_LITERAL_CSTRING("gound.com/"), array); + TestReadNoiseEntries(classifier, GTEST_TABLE_V4, "gound.com/"_ns, array); } TEST(UrlClassifierClassifier, ReadNoiseEntriesV2) @@ -80,6 +79,5 @@ TEST(UrlClassifierClassifier, ReadNoiseEntriesV2) ASSERT_TRUE(rv == NS_OK) << "Fail to build LookupCache"; - TestReadNoiseEntries(classifier, GTEST_TABLE_V2, - NS_LITERAL_CSTRING("helloworld.com/"), array); + TestReadNoiseEntries(classifier, GTEST_TABLE_V2, "helloworld.com/"_ns, array); } diff --git a/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp b/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp index 8a12aadac8d4..b62a852d92b2 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestFailUpdate.cpp @@ -13,10 +13,10 @@ static const char* kFilesInV2[] = {".vlpset", ".sbstore"}; static const char* kFilesInV4[] = {".vlpset", ".metadata"}; -#define GTEST_MALWARE_TABLE_V4 NS_LITERAL_CSTRING("goog-malware-proto") -#define GTEST_PHISH_TABLE_V4 NS_LITERAL_CSTRING("goog-phish-proto") +#define GTEST_MALWARE_TABLE_V4 "goog-malware-proto"_ns +#define GTEST_PHISH_TABLE_V4 "goog-phish-proto"_ns -#define ROOT_DIR NS_LITERAL_STRING("safebrowsing") +#define ROOT_DIR u"safebrowsing"_ns #define SB_FILE(x, y) NS_ConvertUTF8toUTF16(nsPrintfCString("%s%s", x, y)) template diff --git a/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp b/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp index d262462e60ed..73f7f6249ecc 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestLookupCacheV4.cpp @@ -41,13 +41,13 @@ static void TestHasPrefix(const nsCString& aURL, bool aExpectedHas, } TEST(UrlClassifierLookupCacheV4, HasComplete) -{ TestHasPrefix(NS_LITERAL_CSTRING("bravo.com/"), true, true); } +{ TestHasPrefix("bravo.com/"_ns, true, true); } TEST(UrlClassifierLookupCacheV4, HasPrefix) -{ TestHasPrefix(NS_LITERAL_CSTRING("browsing.com/"), true, false); } +{ TestHasPrefix("browsing.com/"_ns, true, false); } TEST(UrlClassifierLookupCacheV4, Nomatch) -{ TestHasPrefix(NS_LITERAL_CSTRING("nomatch.com/"), false, false); } +{ TestHasPrefix("nomatch.com/"_ns, false, false); } // Test an existing .pset should be removed after .vlpset is written TEST(UrlClassifierLookupCacheV4, RemoveOldPset) @@ -55,14 +55,14 @@ TEST(UrlClassifierLookupCacheV4, RemoveOldPset) nsCOMPtr oldPsetFile; NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(oldPsetFile)); - oldPsetFile->AppendNative(NS_LITERAL_CSTRING("safebrowsing")); - oldPsetFile->AppendNative(GTEST_TABLE_V4 + NS_LITERAL_CSTRING(".pset")); + oldPsetFile->AppendNative("safebrowsing"_ns); + oldPsetFile->AppendNative(GTEST_TABLE_V4 + ".pset"_ns); nsCOMPtr newPsetFile; NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(newPsetFile)); - newPsetFile->AppendNative(NS_LITERAL_CSTRING("safebrowsing")); - newPsetFile->AppendNative(GTEST_TABLE_V4 + NS_LITERAL_CSTRING(".vlpset")); + newPsetFile->AppendNative("safebrowsing"_ns); + newPsetFile->AppendNative(GTEST_TABLE_V4 + ".vlpset"_ns); // Create the legacy .pset file nsresult rv = oldPsetFile->Create(nsIFile::NORMAL_FILE_TYPE, 0666); @@ -108,8 +108,8 @@ TEST(UrlClassifierLookupCacheV4, LoadOldPset) { NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(oldPsetFile)); - oldPsetFile->AppendNative(NS_LITERAL_CSTRING("safebrowsing")); - oldPsetFile->AppendNative(GTEST_TABLE_V4 + NS_LITERAL_CSTRING(".pset")); + oldPsetFile->AppendNative("safebrowsing"_ns); + oldPsetFile->AppendNative(GTEST_TABLE_V4 + ".pset"_ns); RefPtr pset = new VariableLengthPrefixSet; pset->SetPrefixes(map); diff --git a/toolkit/components/url-classifier/tests/gtest/TestURLsAndHashing.cpp b/toolkit/components/url-classifier/tests/gtest/TestURLsAndHashing.cpp index 32973609687c..0563c6a77611 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestURLsAndHashing.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestURLsAndHashing.cpp @@ -30,14 +30,14 @@ TEST(URLsAndHashing, FragmentURLWithQuery) { const nsLiteralCString url("a.b.c/1/2.html?param=1"); nsTArray expect = { - nsLiteralCString("a.b.c/1/2.html?param=1"), - nsLiteralCString("a.b.c/1/2.html"), - nsLiteralCString("a.b.c/"), - nsLiteralCString("a.b.c/1/"), - nsLiteralCString("b.c/1/2.html?param=1"), - nsLiteralCString("b.c/1/2.html"), - nsLiteralCString("b.c/"), - nsLiteralCString("b.c/1/"), + "a.b.c/1/2.html?param=1"_ns, + "a.b.c/1/2.html"_ns, + "a.b.c/"_ns, + "a.b.c/1/"_ns, + "b.c/1/2.html?param=1"_ns, + "b.c/1/2.html"_ns, + "b.c/"_ns, + "b.c/1/"_ns, }; VerifyFragments(url, expect); @@ -49,16 +49,11 @@ TEST(URLsAndHashing, FragmentURLWithoutQuery) { const nsLiteralCString url("a.b.c.d.e.f.g/1.html"); nsTArray expect = { - nsLiteralCString("a.b.c.d.e.f.g/1.html"), - nsLiteralCString("a.b.c.d.e.f.g/"), - nsLiteralCString("c.d.e.f.g/1.html"), - nsLiteralCString("c.d.e.f.g/"), - nsLiteralCString("d.e.f.g/1.html"), - nsLiteralCString("d.e.f.g/"), - nsLiteralCString("e.f.g/1.html"), - nsLiteralCString("e.f.g/"), - nsLiteralCString("f.g/1.html"), - nsLiteralCString("f.g/"), + "a.b.c.d.e.f.g/1.html"_ns, "a.b.c.d.e.f.g/"_ns, + "c.d.e.f.g/1.html"_ns, "c.d.e.f.g/"_ns, + "d.e.f.g/1.html"_ns, "d.e.f.g/"_ns, + "e.f.g/1.html"_ns, "e.f.g/"_ns, + "f.g/1.html"_ns, "f.g/"_ns, }; VerifyFragments(url, expect); @@ -68,8 +63,8 @@ TEST(URLsAndHashing, FragmentURLEndWithoutPath) { const nsLiteralCString url("1.2.3.4/?query=string"); nsTArray expect = { - nsLiteralCString("1.2.3.4/?query=string"), - nsLiteralCString("1.2.3.4/"), + "1.2.3.4/?query=string"_ns, + "1.2.3.4/"_ns, }; VerifyFragments(url, expect); diff --git a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp b/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp index c72680a10eab..01d963d9c79c 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestUrlClassifierTableUpdateV4.cpp @@ -14,9 +14,9 @@ #include "Common.h" -#define GTEST_SAFEBROWSING_DIR NS_LITERAL_CSTRING("safebrowsing") -#define GTEST_TABLE NS_LITERAL_CSTRING("gtest-malware-proto") -#define GTEST_PREFIXFILE NS_LITERAL_CSTRING("gtest-malware-proto.vlpset") +#define GTEST_SAFEBROWSING_DIR "safebrowsing"_ns +#define GTEST_TABLE "gtest-malware-proto"_ns +#define GTEST_PREFIXFILE "gtest-malware-proto.vlpset"_ns // This function removes common elements of inArray and outArray from // outArray. This is used by partial update testcase to ensure partial update @@ -141,7 +141,7 @@ static void VerifyPrefixSet(PrefixStringMap& expected) { file->AppendNative(GTEST_SAFEBROWSING_DIR); RefPtr lookup = - new LookupCacheV4(GTEST_TABLE, NS_LITERAL_CSTRING("test"), file); + new LookupCacheV4(GTEST_TABLE, "test"_ns, file); lookup->Init(); file->AppendNative(GTEST_PREFIXFILE); diff --git a/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp b/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp index df42761c7c41..42e88824ce75 100644 --- a/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp +++ b/toolkit/components/url-classifier/tests/gtest/TestVariableLengthPrefixSet.cpp @@ -137,7 +137,7 @@ class UrlClassifierPrefixSetTest : public ::testing::TestWithParam { "browser.safebrowsing.prefixset.max_array_size"; mozilla::Preferences::SetUint(prefKey, GetParam()); - mCache = SetupLookupCache(NS_LITERAL_CSTRING("test")); + mCache = SetupLookupCache("test"_ns); } void TearDown() override { @@ -332,8 +332,7 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveFixedLengthPrefixSet) { // Save { - RefPtr save = - SetupLookupCache(NS_LITERAL_CSTRING("test-save")); + RefPtr save = SetupLookupCache("test-save"_ns); RandomPrefixes(10000, 4, 4, array); @@ -345,14 +344,13 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveFixedLengthPrefixSet) { CheckContent(save, array); NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file)); - file->Append(NS_LITERAL_STRING("test.vlpset")); + file->Append(u"test.vlpset"_ns); save->StoreToFile(file); } // Load { - RefPtr load = - SetupLookupCache(NS_LITERAL_CSTRING("test-load")); + RefPtr load = SetupLookupCache("test-load"_ns); load->LoadFromFile(file); DoExpectedLookup(load, array); @@ -371,8 +369,7 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveVariableLengthPrefixSet) { // Save { - RefPtr save = - SetupLookupCache(NS_LITERAL_CSTRING("test-save")); + RefPtr save = SetupLookupCache("test-save"_ns); RandomPrefixes(10000, 5, 32, array); @@ -384,14 +381,13 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveVariableLengthPrefixSet) { CheckContent(save, array); NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file)); - file->Append(NS_LITERAL_STRING("test.vlpset")); + file->Append(u"test.vlpset"_ns); save->StoreToFile(file); } // Load { - RefPtr load = - SetupLookupCache(NS_LITERAL_CSTRING("test-load")); + RefPtr load = SetupLookupCache("test-load"_ns); load->LoadFromFile(file); DoExpectedLookup(load, array); @@ -410,8 +406,7 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSavePrefixSet) { // Save { - RefPtr save = - SetupLookupCache(NS_LITERAL_CSTRING("test-save")); + RefPtr save = SetupLookupCache("test-save"_ns); // Try to simulate the real case that most prefixes are 4bytes RandomPrefixes(20000, 4, 4, array); @@ -425,14 +420,13 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSavePrefixSet) { CheckContent(save, array); NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file)); - file->Append(NS_LITERAL_STRING("test.vlpset")); + file->Append(u"test.vlpset"_ns); save->StoreToFile(file); } // Load { - RefPtr load = - SetupLookupCache(NS_LITERAL_CSTRING("test-load")); + RefPtr load = SetupLookupCache("test-load"_ns); load->LoadFromFile(file); DoExpectedLookup(load, array); @@ -459,8 +453,7 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveNoDelta) { // Save { - RefPtr save = - SetupLookupCache(NS_LITERAL_CSTRING("test-save")); + RefPtr save = SetupLookupCache("test-save"_ns); PrefixArrayToPrefixStringMap(array, map); save->Build(map); @@ -470,14 +463,13 @@ TEST_P(UrlClassifierPrefixSetTest, LoadSaveNoDelta) { CheckContent(save, array); NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(file)); - file->Append(NS_LITERAL_STRING("test.vlpset")); + file->Append(u"test.vlpset"_ns); save->StoreToFile(file); } // Load { - RefPtr load = - SetupLookupCache(NS_LITERAL_CSTRING("test-load")); + RefPtr load = SetupLookupCache("test-load"_ns); load->LoadFromFile(file); DoExpectedLookup(load, array); diff --git a/toolkit/components/viaduct/ViaductRequest.cpp b/toolkit/components/viaduct/ViaductRequest.cpp index d5a54adaa95f..ec69a7f59670 100644 --- a/toolkit/components/viaduct/ViaductRequest.cpp +++ b/toolkit/components/viaduct/ViaductRequest.cpp @@ -162,23 +162,23 @@ nsCString ConvertMethod( using appservices::httpconfig::protobuf::Request_Method; switch (method) { case Request_Method::Request_Method_GET: - return NS_LITERAL_CSTRING("GET"); + return "GET"_ns; case Request_Method::Request_Method_HEAD: - return NS_LITERAL_CSTRING("HEAD"); + return "HEAD"_ns; case Request_Method::Request_Method_POST: - return NS_LITERAL_CSTRING("POST"); + return "POST"_ns; case Request_Method::Request_Method_PUT: - return NS_LITERAL_CSTRING("PUT"); + return "PUT"_ns; case Request_Method::Request_Method_DELETE: - return NS_LITERAL_CSTRING("DELETE"); + return "DELETE"_ns; case Request_Method::Request_Method_CONNECT: - return NS_LITERAL_CSTRING("CONNECT"); + return "CONNECT"_ns; case Request_Method::Request_Method_OPTIONS: - return NS_LITERAL_CSTRING("OPTIONS"); + return "OPTIONS"_ns; case Request_Method::Request_Method_TRACE: - return NS_LITERAL_CSTRING("TRACE"); + return "TRACE"_ns; } - return NS_LITERAL_CSTRING("UNKNOWN"); + return "UNKNOWN"_ns; } void ViaductRequest::ClearTimers() { diff --git a/toolkit/components/windowwatcher/nsAutoWindowStateHelper.cpp b/toolkit/components/windowwatcher/nsAutoWindowStateHelper.cpp index f1f5d1d50d72..c735f51e49a3 100644 --- a/toolkit/components/windowwatcher/nsAutoWindowStateHelper.cpp +++ b/toolkit/components/windowwatcher/nsAutoWindowStateHelper.cpp @@ -51,8 +51,7 @@ bool nsAutoWindowStateHelper::DispatchEventToChrome(const char* aEventName) { } ErrorResult rv; - RefPtr event = - doc->CreateEvent(NS_LITERAL_STRING("Events"), CallerType::System, rv); + RefPtr event = doc->CreateEvent(u"Events"_ns, CallerType::System, rv); if (rv.Failed()) { rv.SuppressException(); return false; diff --git a/toolkit/components/windowwatcher/nsWindowWatcher.cpp b/toolkit/components/windowwatcher/nsWindowWatcher.cpp index c790385a4453..a460741e6a2d 100644 --- a/toolkit/components/windowwatcher/nsWindowWatcher.cpp +++ b/toolkit/components/windowwatcher/nsWindowWatcher.cpp @@ -1217,13 +1217,11 @@ nsresult nsWindowWatcher::OpenWindowInternal( if (uriToLoad) { // The url notified in the webNavigation.onCreatedNavigationTarget // event. - props->SetPropertyAsACString(NS_LITERAL_STRING("url"), - uriToLoad->GetSpecOrDefault()); + props->SetPropertyAsACString(u"url"_ns, uriToLoad->GetSpecOrDefault()); } - props->SetPropertyAsInterface(NS_LITERAL_STRING("sourceTabDocShell"), - parentDocShell); - props->SetPropertyAsInterface(NS_LITERAL_STRING("createdTabDocShell"), + props->SetPropertyAsInterface(u"sourceTabDocShell"_ns, parentDocShell); + props->SetPropertyAsInterface(u"createdTabDocShell"_ns, ToSupports(newDocShell)); obsSvc->NotifyObservers(static_cast(props), diff --git a/toolkit/components/xulstore/tests/gtest/TestXULStore.cpp b/toolkit/components/xulstore/tests/gtest/TestXULStore.cpp index 78c7778b4d19..50d7f54b8037 100644 --- a/toolkit/components/xulstore/tests/gtest/TestXULStore.cpp +++ b/toolkit/components/xulstore/tests/gtest/TestXULStore.cpp @@ -14,16 +14,16 @@ using mozilla::XULStore::SetValue; TEST(XULStore, SetGetValue) { - nsAutoString doc(NS_LITERAL_STRING("SetGetValue")); - nsAutoString id(NS_LITERAL_STRING("foo")); - nsAutoString attr(NS_LITERAL_STRING("bar")); + nsAutoString doc(u"SetGetValue"_ns); + nsAutoString id(u"foo"_ns); + nsAutoString attr(u"bar"_ns); nsAutoString value; EXPECT_EQ(GetValue(doc, id, attr, value), NS_OK); EXPECT_TRUE(value.EqualsASCII("")); { - nsAutoString value(NS_LITERAL_STRING("baz")); + nsAutoString value(u"baz"_ns); EXPECT_EQ(SetValue(doc, id, attr, value), NS_OK); } @@ -33,13 +33,13 @@ TEST(XULStore, SetGetValue) TEST(XULStore, HasValue) { - nsAutoString doc(NS_LITERAL_STRING("HasValue")); - nsAutoString id(NS_LITERAL_STRING("foo")); - nsAutoString attr(NS_LITERAL_STRING("bar")); + nsAutoString doc(u"HasValue"_ns); + nsAutoString id(u"foo"_ns); + nsAutoString attr(u"bar"_ns); bool hasValue = true; EXPECT_EQ(HasValue(doc, id, attr, hasValue), NS_OK); EXPECT_FALSE(hasValue); - nsAutoString value(NS_LITERAL_STRING("baz")); + nsAutoString value(u"baz"_ns); EXPECT_EQ(SetValue(doc, id, attr, value), NS_OK); EXPECT_EQ(HasValue(doc, id, attr, hasValue), NS_OK); EXPECT_TRUE(hasValue); @@ -47,10 +47,10 @@ TEST(XULStore, HasValue) TEST(XULStore, RemoveValue) { - nsAutoString doc(NS_LITERAL_STRING("RemoveValue")); - nsAutoString id(NS_LITERAL_STRING("foo")); - nsAutoString attr(NS_LITERAL_STRING("bar")); - nsAutoString value(NS_LITERAL_STRING("baz")); + nsAutoString doc(u"RemoveValue"_ns); + nsAutoString id(u"foo"_ns); + nsAutoString attr(u"bar"_ns); + nsAutoString value(u"baz"_ns); EXPECT_EQ(SetValue(doc, id, attr, value), NS_OK); EXPECT_EQ(GetValue(doc, id, attr, value), NS_OK); EXPECT_TRUE(value.EqualsASCII("baz")); @@ -61,12 +61,12 @@ TEST(XULStore, RemoveValue) TEST(XULStore, GetIDsIterator) { - nsAutoString doc(NS_LITERAL_STRING("idIterDoc")); - nsAutoString id1(NS_LITERAL_STRING("id1")); - nsAutoString id2(NS_LITERAL_STRING("id2")); - nsAutoString id3(NS_LITERAL_STRING("id3")); - nsAutoString attr(NS_LITERAL_STRING("attr")); - nsAutoString value(NS_LITERAL_STRING("value")); + nsAutoString doc(u"idIterDoc"_ns); + nsAutoString id1(u"id1"_ns); + nsAutoString id2(u"id2"_ns); + nsAutoString id3(u"id3"_ns); + nsAutoString attr(u"attr"_ns); + nsAutoString value(u"value"_ns); nsAutoString id; // Confirm that the store doesn't have any IDs yet. @@ -83,8 +83,8 @@ TEST(XULStore, GetIDsIterator) // Insert different ID for another doc to confirm that store // won't return it when iterating IDs for our doc. - nsAutoString otherDoc(NS_LITERAL_STRING("otherDoc")); - nsAutoString otherID(NS_LITERAL_STRING("otherID")); + nsAutoString otherDoc(u"otherDoc"_ns); + nsAutoString otherID(u"otherID"_ns); EXPECT_EQ(SetValue(otherDoc, otherID, attr, value), NS_OK); EXPECT_EQ(GetIDs(doc, iter), NS_OK); @@ -102,12 +102,12 @@ TEST(XULStore, GetIDsIterator) TEST(XULStore, GetAttributeIterator) { - nsAutoString doc(NS_LITERAL_STRING("attrIterDoc")); - nsAutoString id(NS_LITERAL_STRING("id")); - nsAutoString attr1(NS_LITERAL_STRING("attr1")); - nsAutoString attr2(NS_LITERAL_STRING("attr2")); - nsAutoString attr3(NS_LITERAL_STRING("attr3")); - nsAutoString value(NS_LITERAL_STRING("value")); + nsAutoString doc(u"attrIterDoc"_ns); + nsAutoString id(u"id"_ns); + nsAutoString attr1(u"attr1"_ns); + nsAutoString attr2(u"attr2"_ns); + nsAutoString attr3(u"attr3"_ns); + nsAutoString value(u"value"_ns); nsAutoString attr; mozilla::UniquePtr iter; @@ -123,8 +123,8 @@ TEST(XULStore, GetAttributeIterator) // Insert different attribute for another ID to confirm that store // won't return it when iterating attributes for our ID. - nsAutoString otherID(NS_LITERAL_STRING("otherID")); - nsAutoString otherAttr(NS_LITERAL_STRING("otherAttr")); + nsAutoString otherID(u"otherID"_ns); + nsAutoString otherAttr(u"otherAttr"_ns); EXPECT_EQ(SetValue(doc, otherID, otherAttr, value), NS_OK); EXPECT_EQ(GetAttrs(doc, id, iter), NS_OK); diff --git a/toolkit/crashreporter/InjectCrashReporter.cpp b/toolkit/crashreporter/InjectCrashReporter.cpp index a846b0468425..d9e6d062e535 100644 --- a/toolkit/crashreporter/InjectCrashReporter.cpp +++ b/toolkit/crashreporter/InjectCrashReporter.cpp @@ -21,7 +21,7 @@ InjectCrashRunnable::InjectCrashRunnable(DWORD pid) nsCOMPtr dll; nsresult rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(dll)); if (NS_SUCCEEDED(rv)) { - dll->Append(NS_LITERAL_STRING("breakpadinjector.dll")); + dll->Append(u"breakpadinjector.dll"_ns); dll->GetPath(mInjectorPath); } } diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp index 13afbfacc8c3..ed441e8b03e1 100644 --- a/toolkit/crashreporter/nsExceptionHandler.cpp +++ b/toolkit/crashreporter/nsExceptionHandler.cpp @@ -1889,10 +1889,10 @@ static nsresult LocateExecutable(nsIFile* aXREDirectory, NS_ENSURE_SUCCESS(rv, rv); # ifdef XP_MACOSX - exePath->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS")); - exePath->Append(NS_LITERAL_STRING("crashreporter.app")); - exePath->Append(NS_LITERAL_STRING("Contents")); - exePath->Append(NS_LITERAL_STRING("MacOS")); + exePath->SetNativeLeafName("MacOS"_ns); + exePath->Append(u"crashreporter.app"_ns); + exePath->Append(u"Contents"_ns); + exePath->Append(u"MacOS"_ns); # endif exePath->AppendNative(aName); @@ -1949,9 +1949,9 @@ nsresult SetExceptionHandler(nsIFile* aXREDirectory, bool force /*=false*/) { #if !defined(MOZ_WIDGET_ANDROID) // Locate the crash reporter executable nsAutoString crashReporterPath_temp; - nsresult rv = LocateExecutable(aXREDirectory, - NS_LITERAL_CSTRING(CRASH_REPORTER_FILENAME), - crashReporterPath_temp); + nsresult rv = + LocateExecutable(aXREDirectory, nsLiteralCString(CRASH_REPORTER_FILENAME), + crashReporterPath_temp); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -2311,8 +2311,7 @@ nsresult SetupExtraData(nsIFile* aAppDataDirectory, } nsAutoCString data; - if (NS_SUCCEEDED(GetOrInit(dataDirectory, - NS_LITERAL_CSTRING("InstallTime") + aBuildID, data, + if (NS_SUCCEEDED(GetOrInit(dataDirectory, "InstallTime"_ns + aBuildID, data, InitInstallTime))) AnnotateCrashReport(Annotation::InstallTime, data); @@ -2321,8 +2320,7 @@ nsresult SetupExtraData(nsIFile* aAppDataDirectory, // crash report with the stored value, since we really want // (now - LastCrash), so we just get a value if it exists, // and store it in a time_t value. - if (NS_SUCCEEDED(GetOrInit(dataDirectory, NS_LITERAL_CSTRING("LastCrash"), - data, nullptr))) { + if (NS_SUCCEEDED(GetOrInit(dataDirectory, "LastCrash"_ns, data, nullptr))) { lastCrashTime = (time_t)atol(data.get()); } @@ -2331,7 +2329,7 @@ nsresult SetupExtraData(nsIFile* aAppDataDirectory, rv = dataDirectory->Clone(getter_AddRefs(lastCrashFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = lastCrashFile->AppendNative(NS_LITERAL_CSTRING("LastCrash")); + rv = lastCrashFile->AppendNative("LastCrash"_ns); NS_ENSURE_SUCCESS(rv, rv); memset(lastCrashTimeFilename, 0, sizeof(lastCrashTimeFilename)); @@ -2413,8 +2411,7 @@ nsresult UnsetExceptionHandler() { } nsresult AnnotateCrashReport(Annotation key, bool data) { - return AnnotateCrashReport( - key, data ? NS_LITERAL_CSTRING("1") : NS_LITERAL_CSTRING("0")); + return AnnotateCrashReport(key, data ? "1"_ns : "0"_ns); } nsresult AnnotateCrashReport(Annotation key, int data) { @@ -2473,7 +2470,7 @@ static void AddCommonAnnotations(AnnotationTable& aAnnotations) { aAnnotations[Annotation::UptimeTS] = uptimeStr; if (memoryReportPath) { - aAnnotations[Annotation::ContainsMemoryReport] = NS_LITERAL_CSTRING("1"); + aAnnotations[Annotation::ContainsMemoryReport] = "1"_ns; } } @@ -2701,7 +2698,7 @@ static nsresult PrefSubmitReports(bool* aSubmitReports, bool writePref) { NS_ENSURE_SUCCESS(rv, rv); uint32_t value = *aSubmitReports ? 1 : 0; - rv = regKey->WriteIntValue(NS_LITERAL_STRING("SubmitCrashReport"), value); + rv = regKey->WriteIntValue(u"SubmitCrashReport"_ns, value); regKey->Close(); return rv; } @@ -2715,7 +2712,7 @@ static nsresult PrefSubmitReports(bool* aSubmitReports, bool writePref) { NS_ConvertUTF8toUTF16(regPath), nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { - rv = regKey->ReadIntValue(NS_LITERAL_STRING("SubmitCrashReport"), &value); + rv = regKey->ReadIntValue(u"SubmitCrashReport"_ns, &value); regKey->Close(); if (NS_SUCCEEDED(rv)) { *aSubmitReports = !!value; @@ -2731,7 +2728,7 @@ static nsresult PrefSubmitReports(bool* aSubmitReports, bool writePref) { return NS_OK; } - rv = regKey->ReadIntValue(NS_LITERAL_STRING("SubmitCrashReport"), &value); + rv = regKey->ReadIntValue(u"SubmitCrashReport"_ns, &value); // default to true on failure if (NS_FAILED(rv)) { value = 1; @@ -2767,8 +2764,8 @@ static nsresult PrefSubmitReports(bool* aSubmitReports, bool writePref) { nsCOMPtr reporterINI; rv = NS_GetSpecialDirectory("UAppData", getter_AddRefs(reporterINI)); NS_ENSURE_SUCCESS(rv, rv); - reporterINI->AppendNative(NS_LITERAL_CSTRING("Crash Reports")); - reporterINI->AppendNative(NS_LITERAL_CSTRING("crashreporter.ini")); + reporterINI->AppendNative("Crash Reports"_ns); + reporterINI->AppendNative("crashreporter.ini"_ns); bool exists; rv = reporterINI->Exists(&exists); @@ -2797,18 +2794,15 @@ static nsresult PrefSubmitReports(bool* aSubmitReports, bool writePref) { nsCOMPtr iniWriter = do_QueryInterface(iniParser); NS_ENSURE_TRUE(iniWriter, NS_ERROR_FAILURE); - rv = iniWriter->SetString( - NS_LITERAL_CSTRING("Crash Reporter"), - NS_LITERAL_CSTRING("SubmitReport"), - *aSubmitReports ? NS_LITERAL_CSTRING("1") : NS_LITERAL_CSTRING("0")); + rv = iniWriter->SetString("Crash Reporter"_ns, "SubmitReport"_ns, + *aSubmitReports ? "1"_ns : "0"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = iniWriter->WriteFile(reporterINI); return rv; } nsAutoCString submitReportValue; - rv = iniParser->GetString(NS_LITERAL_CSTRING("Crash Reporter"), - NS_LITERAL_CSTRING("SubmitReport"), + rv = iniParser->GetString("Crash Reporter"_ns, "SubmitReport"_ns, submitReportValue); // Default to "true" if the pref can't be found. @@ -2884,9 +2878,9 @@ void SetProfileDirectory(nsIFile* aDir) { nsCOMPtr dir; aDir->Clone(getter_AddRefs(dir)); - dir->Append(NS_LITERAL_STRING("crashes")); + dir->Append(u"crashes"_ns); EnsureDirectoryExists(dir); - dir->Append(NS_LITERAL_STRING("events")); + dir->Append(u"events"_ns); EnsureDirectoryExists(dir); SetCrashEventsDir(dir); } @@ -2895,9 +2889,9 @@ void SetUserAppDataDirectory(nsIFile* aDir) { nsCOMPtr dir; aDir->Clone(getter_AddRefs(dir)); - dir->Append(NS_LITERAL_STRING("Crash Reports")); + dir->Append(u"Crash Reports"_ns); EnsureDirectoryExists(dir); - dir->Append(NS_LITERAL_STRING("events")); + dir->Append(u"events"_ns); EnsureDirectoryExists(dir); SetCrashEventsDir(dir); } @@ -2958,8 +2952,7 @@ nsresult GetDefaultMemoryReportFile(nsIFile** aFile) { if (NS_FAILED(rv)) { return rv; } - defaultMemoryReportFile->AppendNative( - NS_LITERAL_CSTRING("memory-report.json.gz")); + defaultMemoryReportFile->AppendNative("memory-report.json.gz"_ns); defaultMemoryReportPath = CreatePathFromFile(defaultMemoryReportFile); if (!defaultMemoryReportPath) { return NS_ERROR_FAILURE; @@ -2985,8 +2978,8 @@ static void FindPendingDir() { "Couldn't get the user appdata directory, crash dumps will go in an " "unusual location"); } else { - pendingDir->Append(NS_LITERAL_STRING("Crash Reports")); - pendingDir->Append(NS_LITERAL_STRING("pending")); + pendingDir->Append(u"Crash Reports"_ns); + pendingDir->Append(u"pending"_ns); #ifdef XP_WIN nsString path; @@ -3060,7 +3053,7 @@ bool GetMinidumpForID(const nsAString& id, nsIFile** minidump) { return false; } - (*minidump)->Append(id + NS_LITERAL_STRING(".dmp")); + (*minidump)->Append(id + u".dmp"_ns); bool exists; if (NS_FAILED((*minidump)->Exists(&exists)) || !exists) { @@ -3083,7 +3076,7 @@ bool GetExtraFileForID(const nsAString& id, nsIFile** extraFile) { return false; } - (*extraFile)->Append(id + NS_LITERAL_STRING(".extra")); + (*extraFile)->Append(id + u".extra"_ns); bool exists; if (NS_FAILED((*extraFile)->Exists(&exists)) || !exists) { @@ -3102,7 +3095,7 @@ bool GetExtraFileForMinidump(nsIFile* minidump, nsIFile** extraFile) { rv = minidump->Clone(getter_AddRefs(extraF)); if (NS_FAILED(rv)) return false; - leafName.Replace(leafName.Length() - 3, 3, NS_LITERAL_STRING("extra")); + leafName.Replace(leafName.Length() - 3, 3, u"extra"_ns); rv = extraF->SetLeafName(leafName); if (NS_FAILED(rv)) return false; @@ -3163,7 +3156,7 @@ bool WriteExtraFile(const nsAString& id, const AnnotationTable& annotations) { return false; } - extra->Append(id + NS_LITERAL_STRING(".extra")); + extra->Append(id + u".extra"_ns); #ifdef XP_WIN nsAutoString path; NS_ENSURE_SUCCESS(extra->GetPath(path), false); @@ -3637,7 +3630,7 @@ static void RenameAdditionalHangMinidump(nsIFile* minidump, childMinidump->GetNativeLeafName(leafName); // turn ".dmp" into "-.dmp - leafName.Insert(NS_LITERAL_CSTRING("-") + name, leafName.Length() - 4); + leafName.Insert("-"_ns + name, leafName.Length() - 4); if (NS_FAILED(minidump->MoveToNative(directory, leafName))) { NS_WARNING("RenameAdditionalHangMinidump failed to move minidump."); diff --git a/toolkit/library/gtest/TestUCRTDepends.cpp b/toolkit/library/gtest/TestUCRTDepends.cpp index 993e622776a5..15008aaa40c9 100644 --- a/toolkit/library/gtest/TestUCRTDepends.cpp +++ b/toolkit/library/gtest/TestUCRTDepends.cpp @@ -80,7 +80,7 @@ TEST(TestUCRTDepends, AppDir) } // Universal CRT files are not in Api Sets on Windows 8. EXPECT_TRUE(StringBeginsWith(nsDependentString(wfd.cFileName), - NS_LITERAL_STRING("api-ms-win-crt-"), + u"api-ms-win-crt-"_ns, nsCaseInsensitiveStringComparator)); } else { // Windows 7 // All files must not be in Api Sets on Windows 7. diff --git a/toolkit/mozapps/extensions/AddonContentPolicy.cpp b/toolkit/mozapps/extensions/AddonContentPolicy.cpp index f29f438aade9..57bffdd681f7 100644 --- a/toolkit/mozapps/extensions/AddonContentPolicy.cpp +++ b/toolkit/mozapps/extensions/AddonContentPolicy.cpp @@ -259,7 +259,7 @@ class CSPValidator final : public nsCSPSrcVisitor { }; bool visitNonceSrc(const nsCSPNonceSrc& src) override { - FormatError("csp.error.illegal-keyword", NS_LITERAL_STRING("'nonce-*'")); + FormatError("csp.error.illegal-keyword", u"'nonce-*'"_ns); return false; }; @@ -425,8 +425,7 @@ AddonContentPolicy::ValidateAddonCSP(const nsAString& aPolicyString, if (!policy->visitDirectiveSrcs(directive, &validator)) { aResult.Assign(validator.GetError()); } else if (!validator.FoundSelf()) { - validator.FormatError("csp.error.missing-source", - NS_LITERAL_STRING("'self'")); + validator.FormatError("csp.error.missing-source", u"'self'"_ns); aResult.Assign(validator.GetError()); } } diff --git a/toolkit/mozapps/extensions/AddonManagerStartup.cpp b/toolkit/mozapps/extensions/AddonManagerStartup.cpp index 3713a7de3f9c..6ffa38cdfc07 100644 --- a/toolkit/mozapps/extensions/AddonManagerStartup.cpp +++ b/toolkit/mozapps/extensions/AddonManagerStartup.cpp @@ -654,7 +654,7 @@ nsresult AddonManagerStartup::EnumerateJARSubtree(nsIURI* uri, } pattern.Append(chr); } - if (!pattern.IsEmpty() && !StringEndsWith(pattern, NS_LITERAL_CSTRING("/"))) { + if (!pattern.IsEmpty() && !StringEndsWith(pattern, "/"_ns)) { pattern.Append('/'); } pattern.Append('*'); diff --git a/toolkit/profile/nsToolkitProfileService.cpp b/toolkit/profile/nsToolkitProfileService.cpp index dc4811313b5e..e0909c78d6cc 100644 --- a/toolkit/profile/nsToolkitProfileService.cpp +++ b/toolkit/profile/nsToolkitProfileService.cpp @@ -53,7 +53,7 @@ using namespace mozilla; #define DEV_EDITION_NAME "dev-edition-default" #define DEFAULT_NAME "default" -#define COMPAT_FILE NS_LITERAL_STRING("compatibility.ini") +#define COMPAT_FILE u"compatibility.ini"_ns #define PROFILE_DB_VERSION "2" #define INSTALL_PREFIX "Install" #define INSTALL_PREFIX_LENGTH 7 @@ -388,7 +388,7 @@ nsToolkitProfileService::nsToolkitProfileService() mUseDedicatedProfile(false), #endif mCreatedAlternateProfile(false), - mStartupReason(NS_LITERAL_STRING("unknown")), + mStartupReason(u"unknown"_ns), mMaybeLockProfile(false), mUpdateChannel(MOZ_STRINGIFY(MOZ_UPDATE_CHANNEL)), mProfileDBExists(false), @@ -732,13 +732,13 @@ nsresult nsToolkitProfileService::Init() { rv = mAppData->Clone(getter_AddRefs(mProfileDBFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = mProfileDBFile->AppendNative(NS_LITERAL_CSTRING("profiles.ini")); + rv = mProfileDBFile->AppendNative("profiles.ini"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = mAppData->Clone(getter_AddRefs(mInstallDBFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = mInstallDBFile->AppendNative(NS_LITERAL_CSTRING("installs.ini")); + rv = mInstallDBFile->AppendNative("installs.ini"_ns); NS_ENSURE_SUCCESS(rv, rv); nsAutoCString buffer; @@ -823,8 +823,7 @@ nsresult nsToolkitProfileService::Init() { return rv; } - rv = ignoreDevEditionProfile->AppendNative( - NS_LITERAL_CSTRING("ignore-dev-edition-profile")); + rv = ignoreDevEditionProfile->AppendNative("ignore-dev-edition-profile"_ns); if (NS_FAILED(rv)) { return rv; } @@ -1236,7 +1235,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( rv = MaybeMakeDefaultDedicatedProfile(profile, &result); NS_ENSURE_SUCCESS(rv, rv); if (result) { - mStartupReason = NS_LITERAL_STRING("restart-claimed-default"); + mStartupReason = u"restart-claimed-default"_ns; mCurrent = profile; } else { @@ -1249,7 +1248,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( rv = Flush(); NS_ENSURE_SUCCESS(rv, rv); - mStartupReason = NS_LITERAL_STRING("restart-skipped-default"); + mStartupReason = u"restart-skipped-default"_ns; *aDidCreate = true; mCreatedAlternateProfile = true; } @@ -1263,11 +1262,11 @@ nsresult nsToolkitProfileService::SelectStartupProfile( } if (EnvHasValue("XRE_RESTARTED_BY_PROFILE_MANAGER")) { - mStartupReason = NS_LITERAL_STRING("profile-manager"); + mStartupReason = u"profile-manager"_ns; } else if (aIsResetting) { - mStartupReason = NS_LITERAL_STRING("profile-reset"); + mStartupReason = u"profile-reset"_ns; } else { - mStartupReason = NS_LITERAL_STRING("restart"); + mStartupReason = u"restart"_ns; } mCurrent = profile; @@ -1308,7 +1307,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( } } - mStartupReason = NS_LITERAL_STRING("argument-profile"); + mStartupReason = u"argument-profile"_ns; GetProfileByDir(lf, nullptr, getter_AddRefs(mCurrent)); NS_ADDREF(*aRootDir = lf); @@ -1385,7 +1384,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( rv = GetProfileByName(nsDependentCString(arg), getter_AddRefs(mCurrent)); if (NS_SUCCEEDED(rv)) { - mStartupReason = NS_LITERAL_STRING("argument-p"); + mStartupReason = u"argument-p"_ns; mCurrent->GetRootDir(aRootDir); mCurrent->GetLocalDir(aLocalDir); @@ -1484,7 +1483,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( rv = MaybeMakeDefaultDedicatedProfile(profile, &result); NS_ENSURE_SUCCESS(rv, rv); if (result) { - mStartupReason = NS_LITERAL_STRING("firstrun-claimed-default"); + mStartupReason = u"firstrun-claimed-default"_ns; mCurrent = profile; rootDir.forget(aRootDir); @@ -1511,7 +1510,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( if ((mUseDedicatedProfile || mUseDevEditionProfile) && mProfiles.getFirst() == mProfiles.getLast()) { nsCOMPtr newProfile; - CreateProfile(nullptr, NS_LITERAL_CSTRING(DEFAULT_NAME), + CreateProfile(nullptr, nsLiteralCString(DEFAULT_NAME), getter_AddRefs(newProfile)); SetNormalDefault(newProfile); } @@ -1520,9 +1519,9 @@ nsresult nsToolkitProfileService::SelectStartupProfile( NS_ENSURE_SUCCESS(rv, rv); if (mCreatedAlternateProfile) { - mStartupReason = NS_LITERAL_STRING("firstrun-skipped-default"); + mStartupReason = u"firstrun-skipped-default"_ns; } else { - mStartupReason = NS_LITERAL_STRING("firstrun-created-default"); + mStartupReason = u"firstrun-created-default"_ns; } // Use the new profile. @@ -1545,7 +1544,7 @@ nsresult nsToolkitProfileService::SelectStartupProfile( // Let the caller know that the profile was selected by default. *aWasDefaultSelection = true; - mStartupReason = NS_LITERAL_STRING("default"); + mStartupReason = u"default"_ns; // Use the selected profile. mCurrent->GetRootDir(aRootDir); @@ -1892,7 +1891,7 @@ nsresult nsToolkitProfileService::CreateTimesInternal(nsIFile* aProfileDir) { rv = aProfileDir->Clone(getter_AddRefs(creationLog)); NS_ENSURE_SUCCESS(rv, rv); - rv = creationLog->AppendNative(NS_LITERAL_CSTRING("times.json")); + rv = creationLog->AppendNative("times.json"_ns); NS_ENSURE_SUCCESS(rv, rv); bool exists = false; diff --git a/toolkit/system/gnome/nsAlertsIconListener.cpp b/toolkit/system/gnome/nsAlertsIconListener.cpp index 44d3d0a4daad..079510baf659 100644 --- a/toolkit/system/gnome/nsAlertsIconListener.cpp +++ b/toolkit/system/gnome/nsAlertsIconListener.cpp @@ -327,7 +327,7 @@ nsresult nsAlertsIconListener::InitAlertAsync(nsIAlertNotification* aAlert, // Workaround for a libnotify bug - blank titles aren't dealt with // properly so we use a space if (title.IsEmpty()) { - mAlertTitle = NS_LITERAL_CSTRING(" "); + mAlertTitle = " "_ns; } else { mAlertTitle = NS_ConvertUTF16toUTF8(title); } diff --git a/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm b/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm index 67714cabf09e..e22eedd86695 100644 --- a/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm +++ b/toolkit/system/osxproxy/nsOSXSystemProxySettings.mm @@ -261,9 +261,9 @@ static void ProxyHasChangedWrapper(SCDynamicStoreRef aStore, CFArrayRef aChanged if (NS_FAILED(rv) || IsInExceptionList(aHost)) { aResult.AssignLiteral("DIRECT"); } else if (proxySocks) { - aResult.Assign(NS_LITERAL_CSTRING("SOCKS ") + proxyHost + nsPrintfCString(":%d", proxyPort)); + aResult.Assign("SOCKS "_ns + proxyHost + nsPrintfCString(":%d", proxyPort)); } else { - aResult.Assign(NS_LITERAL_CSTRING("PROXY ") + proxyHost + nsPrintfCString(":%d", proxyPort)); + aResult.Assign("PROXY "_ns + proxyHost + nsPrintfCString(":%d", proxyPort)); } return NS_OK; diff --git a/toolkit/system/osxproxy/tests/gtest/TestProxyBypassRules.cpp b/toolkit/system/osxproxy/tests/gtest/TestProxyBypassRules.cpp index 4ca88094e454..826011f13ecf 100644 --- a/toolkit/system/osxproxy/tests/gtest/TestProxyBypassRules.cpp +++ b/toolkit/system/osxproxy/tests/gtest/TestProxyBypassRules.cpp @@ -11,56 +11,37 @@ using namespace mozilla::toolkit::system; TEST(OSXProxy, TestProxyBypassRules) { - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("*mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("notmozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.org"), - NS_LITERAL_CSTRING("*mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.com"), - NS_LITERAL_CSTRING("*.mozilla.*"))); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "*mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_FALSE(IsHostProxyEntry("notmozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.org"_ns, "*mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.com"_ns, "*.mozilla.*"_ns)); } TEST(OSXProxy, TestProxyBypassRulesIPv4) { - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.1.*"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.2.*"))); + EXPECT_TRUE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.1.*"_ns)); + EXPECT_FALSE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.2.*"_ns)); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("10.1.2.3"), - NS_LITERAL_CSTRING("10.0.0.0/8"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168/16"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168/17"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168.128/17"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.1.1/32"))); + EXPECT_TRUE(IsHostProxyEntry("10.1.2.3"_ns, "10.0.0.0/8"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.192.1"_ns, "192.168/16"_ns)); + EXPECT_FALSE(IsHostProxyEntry("192.168.192.1"_ns, "192.168/17"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.192.1"_ns, "192.168.128/17"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.1.1/32"_ns)); } TEST(OSXProxy, TestProxyBypassRulesIPv6) { - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/64"))); - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0000:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/80"))); - EXPECT_FALSE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/80"))); - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0000:0000:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/96"))); - EXPECT_FALSE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/96"))); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/64"_ns)); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0000:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/80"_ns)); + EXPECT_FALSE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/80"_ns)); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0000:0000:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/96"_ns)); + EXPECT_FALSE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/96"_ns)); } diff --git a/toolkit/system/unixproxy/nsUnixSystemProxySettings.cpp b/toolkit/system/unixproxy/nsUnixSystemProxySettings.cpp index 3fe3e95c377f..56a53d85798f 100644 --- a/toolkit/system/unixproxy/nsUnixSystemProxySettings.cpp +++ b/toolkit/system/unixproxy/nsUnixSystemProxySettings.cpp @@ -56,9 +56,8 @@ nsUnixSystemProxySettings::GetMainThreadOnly(bool* aMainThreadOnly) { void nsUnixSystemProxySettings::Init() { mGSettings = do_GetService(NS_GSETTINGSSERVICE_CONTRACTID); if (mGSettings) { - mGSettings->GetCollectionForSchema( - NS_LITERAL_CSTRING("org.gnome.system.proxy"), - getter_AddRefs(mProxySettings)); + mGSettings->GetCollectionForSchema("org.gnome.system.proxy"_ns, + getter_AddRefs(mProxySettings)); } } @@ -66,11 +65,9 @@ nsresult nsUnixSystemProxySettings::GetPACURI(nsACString& aResult) { if (mProxySettings) { nsCString proxyMode; // Check if mode is auto - nsresult rv = - mProxySettings->GetString(NS_LITERAL_CSTRING("mode"), proxyMode); + nsresult rv = mProxySettings->GetString("mode"_ns, proxyMode); if (rv == NS_OK && proxyMode.EqualsLiteral("auto")) { - return mProxySettings->GetString(NS_LITERAL_CSTRING("autoconfig-url"), - aResult); + return mProxySettings->GetString("autoconfig-url"_ns, aResult); } } @@ -210,12 +207,12 @@ nsresult nsUnixSystemProxySettings::SetProxyResultFromGSettings( } nsAutoCString host; - rv = proxy_settings->GetString(NS_LITERAL_CSTRING("host"), host); + rv = proxy_settings->GetString("host"_ns, host); NS_ENSURE_SUCCESS(rv, rv); if (host.IsEmpty()) return NS_ERROR_FAILURE; int32_t port; - rv = proxy_settings->GetInt(NS_LITERAL_CSTRING("port"), &port); + rv = proxy_settings->GetInt("port"_ns, &port); NS_ENSURE_SUCCESS(rv, rv); /* When port is 0, proxy is not considered as enabled even if host is set. */ @@ -323,8 +320,7 @@ nsresult nsUnixSystemProxySettings::GetProxyFromGSettings( const nsACString& aScheme, const nsACString& aHost, int32_t aPort, nsACString& aResult) { nsCString proxyMode; - nsresult rv = - mProxySettings->GetString(NS_LITERAL_CSTRING("mode"), proxyMode); + nsresult rv = mProxySettings->GetString("mode"_ns, proxyMode); NS_ENSURE_SUCCESS(rv, rv); // return NS_ERROR_FAILURE when no proxy is set @@ -333,8 +329,8 @@ nsresult nsUnixSystemProxySettings::GetProxyFromGSettings( } nsCOMPtr ignoreList; - if (NS_SUCCEEDED(mProxySettings->GetStringList( - NS_LITERAL_CSTRING("ignore-hosts"), getter_AddRefs(ignoreList))) && + if (NS_SUCCEEDED(mProxySettings->GetStringList("ignore-hosts"_ns, + getter_AddRefs(ignoreList))) && ignoreList) { uint32_t len = 0; ignoreList->GetLength(&len); diff --git a/toolkit/system/windowsproxy/tests/gtest/TestProxyBypassRules.cpp b/toolkit/system/windowsproxy/tests/gtest/TestProxyBypassRules.cpp index 2ac193823cc8..9ccb21638863 100644 --- a/toolkit/system/windowsproxy/tests/gtest/TestProxyBypassRules.cpp +++ b/toolkit/system/windowsproxy/tests/gtest/TestProxyBypassRules.cpp @@ -11,56 +11,37 @@ using namespace mozilla::toolkit::system; TEST(WindowsProxy, TestProxyBypassRules) { - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("*mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("mozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("notmozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.org"), - NS_LITERAL_CSTRING("*mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.org"), - NS_LITERAL_CSTRING("*.mozilla.org"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("www.mozilla.com"), - NS_LITERAL_CSTRING("*.mozilla.*"))); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "*mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("mozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_FALSE(IsHostProxyEntry("notmozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.org"_ns, "*mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.org"_ns, "*.mozilla.org"_ns)); + EXPECT_TRUE(IsHostProxyEntry("www.mozilla.com"_ns, "*.mozilla.*"_ns)); } TEST(WindowsProxy, TestProxyBypassRulesIPv4) { - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.1.*"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.2.*"))); + EXPECT_TRUE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.1.*"_ns)); + EXPECT_FALSE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.2.*"_ns)); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("10.1.2.3"), - NS_LITERAL_CSTRING("10.0.0.0/8"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168/16"))); - EXPECT_FALSE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168/17"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.192.1"), - NS_LITERAL_CSTRING("192.168.128/17"))); - EXPECT_TRUE(IsHostProxyEntry(NS_LITERAL_CSTRING("192.168.1.1"), - NS_LITERAL_CSTRING("192.168.1.1/32"))); + EXPECT_TRUE(IsHostProxyEntry("10.1.2.3"_ns, "10.0.0.0/8"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.192.1"_ns, "192.168/16"_ns)); + EXPECT_FALSE(IsHostProxyEntry("192.168.192.1"_ns, "192.168/17"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.192.1"_ns, "192.168.128/17"_ns)); + EXPECT_TRUE(IsHostProxyEntry("192.168.1.1"_ns, "192.168.1.1/32"_ns)); } TEST(WindowsProxy, TestProxyBypassRulesIPv6) { - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/64"))); - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0000:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/80"))); - EXPECT_FALSE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/80"))); - EXPECT_TRUE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0000:0000:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/96"))); - EXPECT_FALSE(IsHostProxyEntry( - NS_LITERAL_CSTRING("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"), - NS_LITERAL_CSTRING("2001:db8:abcd:0012::0/96"))); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/64"_ns)); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0000:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/80"_ns)); + EXPECT_FALSE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/80"_ns)); + EXPECT_TRUE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0000:0000:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/96"_ns)); + EXPECT_FALSE(IsHostProxyEntry("2001:0DB8:ABCD:0012:0123:4567:89AB:CDEF"_ns, + "2001:db8:abcd:0012::0/96"_ns)); } diff --git a/toolkit/xre/ModuleEvaluator.cpp b/toolkit/xre/ModuleEvaluator.cpp index d62043e6c8ff..ccc4fba6863c 100644 --- a/toolkit/xre/ModuleEvaluator.cpp +++ b/toolkit/xre/ModuleEvaluator.cpp @@ -114,7 +114,7 @@ ModuleEvaluator::ModuleEvaluator() return; } - nsresult rv = winSxSDir->Append(NS_LITERAL_STRING("WinSxS")); + nsresult rv = winSxSDir->Append(u"WinSxS"_ns); MOZ_ASSERT(NS_SUCCEEDED(rv)); if (NS_FAILED(rv)) { return; diff --git a/toolkit/xre/UntrustedModulesProcessor.cpp b/toolkit/xre/UntrustedModulesProcessor.cpp index adabc3b8ccd8..7c95734847f0 100644 --- a/toolkit/xre/UntrustedModulesProcessor.cpp +++ b/toolkit/xre/UntrustedModulesProcessor.cpp @@ -145,8 +145,7 @@ NS_IMPL_ISUPPORTS(UntrustedModulesProcessor, nsIObserver) static const uint32_t kThreadTimeoutMS = 120000; // 2 minutes UntrustedModulesProcessor::UntrustedModulesProcessor() - : mThread(new LazyIdleThread(kThreadTimeoutMS, - NS_LITERAL_CSTRING("Untrusted Modules"), + : mThread(new LazyIdleThread(kThreadTimeoutMS, "Untrusted Modules"_ns, LazyIdleThread::ManualShutdown)), mUnprocessedMutex( "mozilla::UntrustedModulesProcessor::mUnprocessedMutex"), diff --git a/toolkit/xre/nsAppRunner.cpp b/toolkit/xre/nsAppRunner.cpp index 5bd2b9de189d..49d74578c3b9 100644 --- a/toolkit/xre/nsAppRunner.cpp +++ b/toolkit/xre/nsAppRunner.cpp @@ -250,9 +250,9 @@ extern uint32_t gRestartMode; extern void InstallSignalHandlers(const char* ProgramName); -#define FILE_COMPATIBILITY_INFO NS_LITERAL_CSTRING("compatibility.ini") -#define FILE_INVALIDATE_CACHES NS_LITERAL_CSTRING(".purgecaches") -#define FILE_STARTUP_INCOMPLETE NS_LITERAL_STRING(".startup-incomplete") +#define FILE_COMPATIBILITY_INFO "compatibility.ini"_ns +#define FILE_INVALIDATE_CACHES ".purgecaches"_ns +#define FILE_STARTUP_INCOMPLETE u".startup-incomplete"_ns #if defined(MOZ_BLOCK_PROFILE_DOWNGRADE) || defined(MOZ_LAUNCHER_PROCESS) || \ defined(MOZ_DEFAULT_BROWSER_AGENT) @@ -799,7 +799,7 @@ NS_IMETHODIMP nsXULAppInfo::GetAccessibilityInstantiator(nsAString& aInstantiator) { #if defined(ACCESSIBILITY) && defined(XP_WIN) if (!GetAccService()) { - aInstantiator = NS_LITERAL_STRING(""); + aInstantiator = u""_ns; return NS_OK; } nsAutoString ipClientInfo; @@ -815,7 +815,7 @@ nsXULAppInfo::GetAccessibilityInstantiator(nsAString& aInstantiator) { } } #else - aInstantiator = NS_LITERAL_STRING(""); + aInstantiator = u""_ns; #endif return NS_OK; } @@ -2220,7 +2220,7 @@ static void SubmitDowngradeTelemetry(const nsCString& aLastVersion, nsCOMPtr sysInfo = do_GetService("@mozilla.org/system-info;1"); NS_ENSURE_TRUE_VOID(sysInfo); - sysInfo->GetPropertyAsACString(NS_LITERAL_STRING("arch"), arch); + sysInfo->GetPropertyAsACString(u"arch"_ns, arch); time_t now; time(&now); @@ -2251,7 +2251,7 @@ static void SubmitDowngradeTelemetry(const nsCString& aLastVersion, nsCOMPtr pingFile; rv = NS_GetSpecialDirectory(XRE_USER_APP_DATA_DIR, getter_AddRefs(pingFile)); NS_ENSURE_SUCCESS_VOID(rv); - rv = pingFile->Append(NS_LITERAL_STRING("Pending Pings")); + rv = pingFile->Append(u"Pending Pings"_ns); NS_ENSURE_SUCCESS_VOID(rv); rv = pingFile->Create(nsIFile::DIRECTORY_TYPE, 0755); if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) { @@ -2264,9 +2264,9 @@ static void SubmitDowngradeTelemetry(const nsCString& aLastVersion, rv = NS_GetSpecialDirectory(NS_GRE_BIN_DIR, getter_AddRefs(pingSender)); NS_ENSURE_SUCCESS_VOID(rv); # ifdef XP_WIN - pingSender->Append(NS_LITERAL_STRING("pingsender.exe")); + pingSender->Append(u"pingsender.exe"_ns); # else - pingSender->Append(NS_LITERAL_STRING("pingsender")); + pingSender->Append(u"pingsender"_ns); # endif bool exists; @@ -2380,7 +2380,7 @@ static ReturnAbortOnError CheckDowngrade(nsIFile* aProfileDir, rv = aProfileDir->Clone(getter_AddRefs(prefsFile)); NS_ENSURE_SUCCESS(rv, rv); - rv = prefsFile->Append(NS_LITERAL_STRING("prefs.js")); + rv = prefsFile->Append(u"prefs.js"_ns); NS_ENSURE_SUCCESS(rv, rv); rv = prefSvc->ReadUserPrefsFromFile(prefsFile); @@ -2686,7 +2686,7 @@ static bool RemoveComponentRegistries(nsIFile* aProfileDir, if (!file) return false; if (aRemoveEMFiles) { - file->SetNativeLeafName(NS_LITERAL_CSTRING("extensions.ini")); + file->SetNativeLeafName("extensions.ini"_ns); file->Remove(false); } @@ -2699,13 +2699,13 @@ static bool RemoveComponentRegistries(nsIFile* aProfileDir, # define PLATFORM_FASL_SUFFIX ".mfl" #endif - file->AppendNative(NS_LITERAL_CSTRING("XUL" PLATFORM_FASL_SUFFIX)); + file->AppendNative(nsLiteralCString("XUL" PLATFORM_FASL_SUFFIX)); file->Remove(false); - file->SetNativeLeafName(NS_LITERAL_CSTRING("XPC" PLATFORM_FASL_SUFFIX)); + file->SetNativeLeafName(nsLiteralCString("XPC" PLATFORM_FASL_SUFFIX)); file->Remove(false); - file->SetNativeLeafName(NS_LITERAL_CSTRING("startupCache")); + file->SetNativeLeafName("startupCache"_ns); nsresult rv = file->Remove(true); return NS_SUCCEEDED(rv) || rv == NS_ERROR_FILE_TARGET_DOES_NOT_EXIST || rv == NS_ERROR_FILE_NOT_FOUND; @@ -2722,7 +2722,7 @@ static void MakeOrSetMinidumpPath(nsIFile* profD) { if (dumpD) { bool fileExists; // XXX: do some more error checking here - dumpD->Append(NS_LITERAL_STRING("minidumps")); + dumpD->Append(u"minidumps"_ns); dumpD->Exists(&fileExists); if (!fileExists) { nsresult rv = dumpD->Create(nsIFile::DIRECTORY_TYPE, 0700); @@ -3280,8 +3280,8 @@ int XREMain::XRE_mainInit(bool* aExitFlag) { nsCOMPtr overrideini; if (NS_SUCCEEDED( mDirProvider.GetAppDir()->Clone(getter_AddRefs(overrideini))) && - NS_SUCCEEDED(overrideini->AppendNative( - NS_LITERAL_CSTRING("crashreporter-override.ini")))) { + NS_SUCCEEDED( + overrideini->AppendNative("crashreporter-override.ini"_ns))) { #ifdef XP_WIN nsAutoString overridePathW; overrideini->GetPath(overridePathW); @@ -4399,7 +4399,7 @@ nsresult XREMain::XRE_mainRun() { if (gDoMigration) { nsCOMPtr file; mDirProvider.GetAppDir()->Clone(getter_AddRefs(file)); - file->AppendNative(NS_LITERAL_CSTRING("override.ini")); + file->AppendNative("override.ini"_ns); nsINIParser parser; nsresult rv = parser.Init(file); // if override.ini doesn't exist, also check for distribution.ini @@ -4407,7 +4407,7 @@ nsresult XREMain::XRE_mainRun() { bool persistent; mDirProvider.GetFile(XRE_APP_DISTRIBUTION_DIR, &persistent, getter_AddRefs(file)); - file->AppendNative(NS_LITERAL_CSTRING("distribution.ini")); + file->AppendNative("distribution.ini"_ns); rv = parser.Init(file); } if (NS_SUCCEEDED(rv)) { @@ -4791,7 +4791,7 @@ int XREMain::XRE_main(int argc, char* argv[], const BootstrapConfig& aConfig) { nsCOMPtr parent; greDir->GetParent(getter_AddRefs(parent)); greDir = parent.forget(); - greDir->AppendNative(NS_LITERAL_CSTRING("Resources")); + greDir->AppendNative("Resources"_ns); #endif mAppData->xreDirectory = greDir; @@ -5231,13 +5231,13 @@ void setASanReporterPath(nsIFile* aDir) { nsCOMPtr dir; aDir->Clone(getter_AddRefs(dir)); - dir->Append(NS_LITERAL_STRING("asan")); + dir->Append(u"asan"_ns); nsresult rv = dir->Create(nsIFile::DIRECTORY_TYPE, 0700); if (NS_WARN_IF(NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS)) { MOZ_CRASH("[ASan Reporter] Unable to create crash directory."); } - dir->Append(NS_LITERAL_STRING("ff_asan_log")); + dir->Append(u"ff_asan_log"_ns); # ifdef XP_WIN nsAutoString nspathW; diff --git a/toolkit/xre/nsAppStartupNotifier.cpp b/toolkit/xre/nsAppStartupNotifier.cpp index f2a5ca59e05d..3bc1f5dac5b5 100644 --- a/toolkit/xre/nsAppStartupNotifier.cpp +++ b/toolkit/xre/nsAppStartupNotifier.cpp @@ -38,7 +38,7 @@ nsresult nsAppStartupNotifier::NotifyObservers(const char* aCategory) { // If we see the word "service," in the beginning // of the contractId then we create it as a service // if not we do a createInstance - if (StringBeginsWith(contractId, NS_LITERAL_CSTRING("service,"))) { + if (StringBeginsWith(contractId, "service,"_ns)) { startupInstance = do_GetService(contractId.get() + 8, &rv); } else { startupInstance = do_CreateInstance(contractId.get(), &rv); diff --git a/toolkit/xre/nsConsoleWriter.cpp b/toolkit/xre/nsConsoleWriter.cpp index 0a2c0c342893..d89ea3bde31d 100644 --- a/toolkit/xre/nsConsoleWriter.cpp +++ b/toolkit/xre/nsConsoleWriter.cpp @@ -32,7 +32,7 @@ void WriteConsoleLog() { rv = nsXREDirProvider::GetUserAppDataDirectory(getter_AddRefs(lfile)); if (NS_FAILED(rv)) return; - lfile->AppendNative(NS_LITERAL_CSTRING("console.log")); + lfile->AppendNative("console.log"_ns); } PRFileDesc* file; diff --git a/toolkit/xre/nsNativeAppSupportUnix.cpp b/toolkit/xre/nsNativeAppSupportUnix.cpp index d8b32b4c27c9..9851a9979314 100644 --- a/toolkit/xre/nsNativeAppSupportUnix.cpp +++ b/toolkit/xre/nsNativeAppSupportUnix.cpp @@ -577,8 +577,7 @@ nsNativeAppSupportUnix::Start(bool* aRetVal) { // is what Breakpad does nsAutoCString leafName; rv = executablePath->GetNativeLeafName(leafName); - if (NS_SUCCEEDED(rv) && - StringEndsWith(leafName, NS_LITERAL_CSTRING("-bin"))) { + if (NS_SUCCEEDED(rv) && StringEndsWith(leafName, "-bin"_ns)) { leafName.SetLength(leafName.Length() - strlen("-bin")); executablePath->SetNativeLeafName(leafName); } @@ -626,7 +625,7 @@ nsNativeAppSupportUnix::Start(bool* aRetVal) { if (pw && pw->pw_name) { userName = pw->pw_name; } else { - userName = NS_LITERAL_CSTRING("nobody"); + userName = "nobody"_ns; MOZ_LOG( sMozSMLog, LogLevel::Warning, ("Could not determine user-name. Falling back to %s.", userName.get())); diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp index 6af227711642..3694ec6f364c 100644 --- a/toolkit/xre/nsUpdateDriver.cpp +++ b/toolkit/xre/nsUpdateDriver.cpp @@ -179,7 +179,7 @@ static bool GetFile(nsIFile* dir, const nsACString& name, } static bool GetStatusFile(nsIFile* dir, nsCOMPtr& result) { - return GetFile(dir, NS_LITERAL_CSTRING("update.status"), result); + return GetFile(dir, "update.status"_ns, result); } /** @@ -260,7 +260,7 @@ static UpdateStatus GetUpdateStatus(nsIFile* dir, } static bool GetVersionFile(nsIFile* dir, nsCOMPtr& result) { - return GetFile(dir, NS_LITERAL_CSTRING("update.version"), result); + return GetFile(dir, "update.version"_ns, result); } // Compares the current application version with the update's application @@ -326,7 +326,7 @@ static void ApplyUpdate(nsIFile* greDir, nsIFile* updateDir, nsIFile* appDir, nsAutoCString updateDirPath; #if defined(XP_WIN) // Get an nsIFile reference for the updater in the installation dir. - if (!GetFile(greDir, NS_LITERAL_CSTRING(UPDATER_BIN), updater)) { + if (!GetFile(greDir, nsLiteralCString(UPDATER_BIN), updater)) { return; } @@ -347,18 +347,18 @@ static void ApplyUpdate(nsIFile* greDir, nsIFile* updateDir, nsIFile* appDir, updateDirPath = NS_ConvertUTF16toUTF8(updateDirPathW); #elif defined(XP_MACOSX) // Get an nsIFile reference for the updater in the installation dir. - if (!GetFile(appDir, NS_LITERAL_CSTRING(UPDATER_APP), updater)) { + if (!GetFile(appDir, nsLiteralCString(UPDATER_APP), updater)) { return; } - rv = updater->AppendNative(NS_LITERAL_CSTRING("Contents")); + rv = updater->AppendNative("Contents"_ns); if (NS_FAILED(rv)) { return; } - rv = updater->AppendNative(NS_LITERAL_CSTRING("MacOS")); + rv = updater->AppendNative("MacOS"_ns); if (NS_FAILED(rv)) { return; } - rv = updater->AppendNative(NS_LITERAL_CSTRING(UPDATER_BIN)); + rv = updater->AppendNative(nsLiteralCString(UPDATER_BIN)); if (NS_FAILED(rv)) { return; } @@ -376,7 +376,7 @@ static void ApplyUpdate(nsIFile* greDir, nsIFile* updateDir, nsIFile* appDir, } #else // Get an nsIFile reference for the updater in the installation dir. - if (!GetFile(greDir, NS_LITERAL_CSTRING(UPDATER_BIN), updater)) { + if (!GetFile(greDir, nsLiteralCString(UPDATER_BIN), updater)) { return; } @@ -442,9 +442,9 @@ static void ApplyUpdate(nsIFile* greDir, nsIFile* updateDir, nsIFile* appDir, } else { // Get the directory where the update is staged or will be staged. #if defined(XP_MACOSX) - if (!GetFile(updateDir, NS_LITERAL_CSTRING("Updated.app"), updatedDir)) { + if (!GetFile(updateDir, "Updated.app"_ns, updatedDir)) { #else - if (!GetFile(appDir, NS_LITERAL_CSTRING("updated"), updatedDir)) { + if (!GetFile(appDir, "updated"_ns, updatedDir)) { #endif return; } @@ -661,9 +661,9 @@ nsresult ProcessUpdates(nsIFile* greDir, nsIFile* appDir, nsIFile* updRootDir, nsCOMPtr updatesDir; rv = updRootDir->Clone(getter_AddRefs(updatesDir)); NS_ENSURE_SUCCESS(rv, rv); - rv = updatesDir->AppendNative(NS_LITERAL_CSTRING("updates")); + rv = updatesDir->AppendNative("updates"_ns); NS_ENSURE_SUCCESS(rv, rv); - rv = updatesDir->AppendNative(NS_LITERAL_CSTRING("0")); + rv = updatesDir->AppendNative("0"_ns); NS_ENSURE_SUCCESS(rv, rv); // Return early since there isn't a valid update when the update application diff --git a/toolkit/xre/nsXREDirProvider.cpp b/toolkit/xre/nsXREDirProvider.cpp index 62b5694e99e8..d8f2171d7c1c 100644 --- a/toolkit/xre/nsXREDirProvider.cpp +++ b/toolkit/xre/nsXREDirProvider.cpp @@ -161,7 +161,7 @@ nsresult nsXREDirProvider::Initialize( #endif mGREDir->Clone(getter_AddRefs(mGREBinDir)); #ifdef XP_MACOSX - mGREBinDir->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS")); + mGREBinDir->SetNativeLeafName("MacOS"_ns); #endif if (!mProfileDir) { @@ -245,7 +245,7 @@ nsresult nsXREDirProvider::GetUserProfilesRootDir(nsIFile** aResult) { if (NS_SUCCEEDED(rv)) { #if !defined(XP_UNIX) || defined(XP_MACOSX) - rv = file->AppendNative(NS_LITERAL_CSTRING("Profiles")); + rv = file->AppendNative("Profiles"_ns); #endif // We must create the profile directory here if it does not exist. nsresult tmp = EnsureDirectoryExists(file); @@ -263,7 +263,7 @@ nsresult nsXREDirProvider::GetUserProfilesLocalDir(nsIFile** aResult) { if (NS_SUCCEEDED(rv)) { #if !defined(XP_UNIX) || defined(XP_MACOSX) - rv = file->AppendNative(NS_LITERAL_CSTRING("Profiles")); + rv = file->AppendNative("Profiles"_ns); #endif // We must create the profile directory here if it does not exist. nsresult tmp = EnsureDirectoryExists(file); @@ -291,7 +291,7 @@ static nsresult GetSystemParentDirectory(nsIFile** aFile) { rv = GetOSXFolderType(kOnSystemDisk, kApplicationSupportFolderType, getter_AddRefs(localDir)); if (NS_SUCCEEDED(rv)) { - rv = localDir->AppendNative(NS_LITERAL_CSTRING("Mozilla")); + rv = localDir->AppendNative("Mozilla"_ns); } # else NS_NAMED_LITERAL_CSTRING(dirname, @@ -370,8 +370,8 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, // directory (if applicable) in NS_APP_PREFS_DEFAULTS_DIR_LIST. rv = mGREDir->Clone(getter_AddRefs(file)); if (NS_SUCCEEDED(rv)) { - rv = file->AppendNative(NS_LITERAL_CSTRING("defaults")); - if (NS_SUCCEEDED(rv)) rv = file->AppendNative(NS_LITERAL_CSTRING("pref")); + rv = file->AppendNative("defaults"_ns); + if (NS_SUCCEEDED(rv)) rv = file->AppendNative("pref"_ns); } } else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_DIR) || !strcmp(aProperty, XRE_USER_APP_DATA_DIR)) { @@ -390,9 +390,9 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, rv = GetUserDataDirectoryHome(getter_AddRefs(localDir), false); if (NS_SUCCEEDED(rv)) { # if defined(XP_MACOSX) - rv = localDir->AppendNative(NS_LITERAL_CSTRING("Mozilla")); + rv = localDir->AppendNative("Mozilla"_ns); # else - rv = localDir->AppendNative(NS_LITERAL_CSTRING(".mozilla")); + rv = localDir->AppendNative(".mozilla"_ns); # endif } if (NS_SUCCEEDED(rv)) { @@ -407,7 +407,7 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, } else if (!strcmp(aProperty, NS_APP_APPLICATION_REGISTRY_FILE)) { rv = GetUserAppDataDirectory(getter_AddRefs(file)); if (NS_SUCCEEDED(rv)) - rv = file->AppendNative(NS_LITERAL_CSTRING(APP_REGISTRY_NAME)); + rv = file->AppendNative(nsLiteralCString(APP_REGISTRY_NAME)); } else if (!strcmp(aProperty, NS_APP_USER_PROFILES_ROOT_DIR)) { rv = GetUserProfilesRootDir(getter_AddRefs(file)); } else if (!strcmp(aProperty, NS_APP_USER_PROFILES_LOCAL_ROOT_DIR)) { @@ -471,12 +471,10 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, } else if (!strcmp(aProperty, XRE_APP_DISTRIBUTION_DIR)) { bool persistent = false; rv = GetFile(NS_GRE_DIR, &persistent, getter_AddRefs(file)); - if (NS_SUCCEEDED(rv)) - rv = file->AppendNative(NS_LITERAL_CSTRING("distribution")); + if (NS_SUCCEEDED(rv)) rv = file->AppendNative("distribution"_ns); } else if (!strcmp(aProperty, XRE_APP_FEATURES_DIR)) { rv = GetAppDir()->Clone(getter_AddRefs(file)); - if (NS_SUCCEEDED(rv)) - rv = file->AppendNative(NS_LITERAL_CSTRING("features")); + if (NS_SUCCEEDED(rv)) rv = file->AppendNative("features"_ns); } else if (!strcmp(aProperty, XRE_ADDON_APP_DIR)) { nsCOMPtr dirsvc( do_GetService("@mozilla.org/file/directory_service;1", &rv)); @@ -504,7 +502,7 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, // We need to allow component, xpt, and chrome registration to // occur prior to the profile-after-change notification. if (!strcmp(aProperty, NS_APP_USER_CHROME_DIR)) { - rv = file->AppendNative(NS_LITERAL_CSTRING("chrome")); + rv = file->AppendNative("chrome"_ns); } } @@ -519,11 +517,11 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent, if (!strcmp(aProperty, NS_APP_PREFS_50_DIR)) { rv = NS_OK; } else if (!strcmp(aProperty, NS_APP_PREFS_50_FILE)) { - rv = file->AppendNative(NS_LITERAL_CSTRING("prefs.js")); + rv = file->AppendNative("prefs.js"_ns); } else if (!strcmp(aProperty, NS_APP_PREFS_OVERRIDE_DIR)) { rv = mProfileDir->Clone(getter_AddRefs(file)); nsresult tmp = - file->AppendNative(NS_LITERAL_CSTRING(PREF_OVERRIDE_DIRNAME)); + file->AppendNative(nsLiteralCString(PREF_OVERRIDE_DIRNAME)); if (NS_FAILED(tmp)) { rv = tmp; } @@ -721,7 +719,7 @@ static already_AddRefed GetProcessSandboxTempDir( return nullptr; } - rv = localFile->Append(NS_LITERAL_STRING("Temp-") + tempDirSuffix); + rv = localFile->Append(u"Temp-"_ns + tempDirSuffix); if (NS_WARN_IF(NS_FAILED(rv))) { return nullptr; } @@ -1272,11 +1270,11 @@ nsresult nsXREDirProvider::GetUpdateRootDir(nsIFile** aResult, nsDependentCString(hasVendor ? GetAppVendor() : GetAppName())))) { return NS_ERROR_FAILURE; } - } else if (NS_FAILED(localDir->AppendNative(NS_LITERAL_CSTRING("Mozilla")))) { + } else if (NS_FAILED(localDir->AppendNative("Mozilla"_ns))) { return NS_ERROR_FAILURE; } - if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("updates"))) || + if (NS_FAILED(localDir->Append(u"updates"_ns)) || NS_FAILED(localDir->AppendRelativePath(appDirPath))) { return NS_ERROR_FAILURE; } @@ -1453,8 +1451,7 @@ nsresult nsXREDirProvider::GetUserDataDirectoryHome(nsIFile** aFile, } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, getter_AddRefs(localDir)); - if (NS_SUCCEEDED(rv)) - rv = localDir->AppendNative(NS_LITERAL_CSTRING(".cache")); + if (NS_SUCCEEDED(rv)) rv = localDir->AppendNative(".cache"_ns); } } else { rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true, diff --git a/toolkit/xre/test/gtest/TestCompatVersionCompare.cpp b/toolkit/xre/test/gtest/TestCompatVersionCompare.cpp index c42353aa832d..bce64aacd5fe 100644 --- a/toolkit/xre/test/gtest/TestCompatVersionCompare.cpp +++ b/toolkit/xre/test/gtest/TestCompatVersionCompare.cpp @@ -49,6 +49,5 @@ TEST(CompatVersionCompare, CompareVersionChange) // Check that if the last run was safe mode then we consider this an upgrade. CheckCompatVersionCompare( - NS_LITERAL_CSTRING("Safe Mode"), - NS_LITERAL_CSTRING("67.0.1_20000000000000/20000000000000"), false, false); + "Safe Mode"_ns, "67.0.1_20000000000000/20000000000000"_ns, false, false); } diff --git a/tools/fuzzing/interface/harness/FuzzerTestHarness.h b/tools/fuzzing/interface/harness/FuzzerTestHarness.h index d3c996e41a80..1530ac86c557 100644 --- a/tools/fuzzing/interface/harness/FuzzerTestHarness.h +++ b/tools/fuzzing/interface/harness/FuzzerTestHarness.h @@ -128,7 +128,7 @@ class ScopedXPCOM final : public nsIDirectoryServiceProvider2 { getter_AddRefs(profD)); NS_ENSURE_SUCCESS(rv, nullptr); - rv = profD->Append(NS_LITERAL_STRING("cpp-unit-profd")); + rv = profD->Append(u"cpp-unit-profd"_ns); NS_ENSURE_SUCCESS(rv, nullptr); rv = profD->CreateUnique(nsIFile::DIRECTORY_TYPE, 0755); @@ -170,7 +170,7 @@ class ScopedXPCOM final : public nsIDirectoryServiceProvider2 { nsAutoCString leafName; mGREBinD->GetNativeLeafName(leafName); if (leafName.EqualsLiteral("Resources")) { - mGREBinD->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS")); + mGREBinD->SetNativeLeafName("MacOS"_ns); } #endif diff --git a/tools/profiler/core/ProfilerBacktrace.cpp b/tools/profiler/core/ProfilerBacktrace.cpp index 65f2b0d82a0a..21099b5e42db 100644 --- a/tools/profiler/core/ProfilerBacktrace.cpp +++ b/tools/profiler/core/ProfilerBacktrace.cpp @@ -41,7 +41,7 @@ void ProfilerBacktrace::StreamJSON(SpliceableJSONWriter& aWriter, // any JitReturnAddr entries. For synchronous samples, JIT frames get expanded // at sample time. StreamSamplesAndMarkers(mName.get(), mThreadId, *mProfileBuffer, aWriter, - NS_LITERAL_CSTRING(""), aProcessStartTime, + ""_ns, aProcessStartTime, /* aRegisterTime */ mozilla::TimeStamp(), /* aUnregisterTime */ mozilla::TimeStamp(), /* aSinceTime */ 0, aUniqueStacks); diff --git a/tools/profiler/core/platform.cpp b/tools/profiler/core/platform.cpp index f605914250c7..b5e12f4811f4 100644 --- a/tools/profiler/core/platform.cpp +++ b/tools/profiler/core/platform.cpp @@ -2522,7 +2522,7 @@ static void StreamMetaJSCustomObject( aWriter.StringElement(NS_ConvertUTF16toUTF8(ext->Name()).get()); - auto url = ext->GetURL(NS_LITERAL_STRING("")); + auto url = ext->GetURL(u""_ns); if (url.isOk()) { aWriter.StringElement(NS_ConvertUTF16toUTF8(url.unwrap()).get()); } diff --git a/tools/profiler/core/shared-libraries-win32.cc b/tools/profiler/core/shared-libraries-win32.cc index b8c95d2e7b63..43b2141c4ed8 100644 --- a/tools/profiler/core/shared-libraries-win32.cc +++ b/tools/profiler/core/shared-libraries-win32.cc @@ -171,13 +171,11 @@ SharedLibraryInfo SharedLibraryInfo::GetInfoForSelf() { !mozilla::IsWin8OrLater() && ::GetModuleHandle(kNvidiaShimDriver) && !::GetModuleHandle(kNvidiaInitDriver)) { NS_NAMED_LITERAL_STRING(pdbNameStr, "detoured.pdb"); - SharedLibrary shlib( - (uintptr_t)module.lpBaseOfDll, - (uintptr_t)module.lpBaseOfDll + module.SizeOfImage, - 0, // DLLs are always mapped at offset 0 on Windows - NS_LITERAL_CSTRING("000000000000000000000000000000000"), - moduleNameStr, modulePathStr, pdbNameStr, pdbNameStr, - NS_LITERAL_CSTRING(""), ""); + SharedLibrary shlib((uintptr_t)module.lpBaseOfDll, + (uintptr_t)module.lpBaseOfDll + module.SizeOfImage, + 0, // DLLs are always mapped at offset 0 on Windows + "000000000000000000000000000000000"_ns, moduleNameStr, + modulePathStr, pdbNameStr, pdbNameStr, ""_ns, ""); sharedLibraryInfo.AddSharedLibrary(shlib); continue; } diff --git a/tools/profiler/gecko/nsProfiler.cpp b/tools/profiler/gecko/nsProfiler.cpp index 267e7eaf5df3..643d87bf7b26 100644 --- a/tools/profiler/gecko/nsProfiler.cpp +++ b/tools/profiler/gecko/nsProfiler.cpp @@ -850,7 +850,7 @@ RefPtr nsProfiler::StartGathering( self->GatheredOOPProfile(profileString); }, [self](ipc::ResponseRejectReason&& aReason) { - self->GatheredOOPProfile(NS_LITERAL_CSTRING("")); + self->GatheredOOPProfile(""_ns); }); } if (!mPendingProfiles) { diff --git a/tools/profiler/tests/gtest/GeckoProfiler.cpp b/tools/profiler/tests/gtest/GeckoProfiler.cpp index 7dc2725a3dca..309b8039b331 100644 --- a/tools/profiler/tests/gtest/GeckoProfiler.cpp +++ b/tools/profiler/tests/gtest/GeckoProfiler.cpp @@ -48,28 +48,24 @@ TEST(BaseProfiler, BlocksRingBuffer) &buffer[MBSize], MakePowerOfTwo32()); { - nsCString cs(NS_LITERAL_CSTRING("nsCString")); - nsString s(NS_LITERAL_STRING("nsString")); - nsAutoCString acs(NS_LITERAL_CSTRING("nsAutoCString")); - nsAutoString as(NS_LITERAL_STRING("nsAutoString")); - nsAutoCStringN<8> acs8(NS_LITERAL_CSTRING("nsAutoCStringN")); - nsAutoStringN<8> as8(NS_LITERAL_STRING("nsAutoStringN")); + nsCString cs("nsCString"_ns); + nsString s(u"nsString"_ns); + nsAutoCString acs("nsAutoCString"_ns); + nsAutoString as(u"nsAutoString"_ns); + nsAutoCStringN<8> acs8("nsAutoCStringN"_ns); + nsAutoStringN<8> as8(u"nsAutoStringN"_ns); JS::UniqueChars jsuc = JS_smprintf("%s", "JS::UniqueChars"); rb.PutObjects(cs, s, acs, as, acs8, as8, jsuc); } rb.ReadEach([](ProfileBufferEntryReader& aER) { - ASSERT_EQ(aER.ReadObject(), NS_LITERAL_CSTRING("nsCString")); - ASSERT_EQ(aER.ReadObject(), NS_LITERAL_STRING("nsString")); - ASSERT_EQ(aER.ReadObject(), - NS_LITERAL_CSTRING("nsAutoCString")); - ASSERT_EQ(aER.ReadObject(), - NS_LITERAL_STRING("nsAutoString")); - ASSERT_EQ(aER.ReadObject>(), - NS_LITERAL_CSTRING("nsAutoCStringN")); - ASSERT_EQ(aER.ReadObject>(), - NS_LITERAL_STRING("nsAutoStringN")); + ASSERT_EQ(aER.ReadObject(), "nsCString"_ns); + ASSERT_EQ(aER.ReadObject(), u"nsString"_ns); + ASSERT_EQ(aER.ReadObject(), "nsAutoCString"_ns); + ASSERT_EQ(aER.ReadObject(), u"nsAutoString"_ns); + ASSERT_EQ(aER.ReadObject>(), "nsAutoCStringN"_ns); + ASSERT_EQ(aER.ReadObject>(), u"nsAutoStringN"_ns); auto jsuc2 = aER.ReadObject(); ASSERT_TRUE(!!jsuc2); ASSERT_TRUE(strcmp(jsuc2.get(), "JS::UniqueChars") == 0); @@ -673,8 +669,7 @@ TEST(GeckoProfiler, Markers) PROFILER_ADD_MARKER_WITH_PAYLOAD( "DOMEventMarkerPayload marker", OTHER, DOMEventMarkerPayload, - (NS_LITERAL_STRING("dom event"), ts1, "category", TRACING_EVENT, - mozilla::Nothing())); + (u"dom event"_ns, ts1, "category", TRACING_EVENT, mozilla::Nothing())); { const char gcMajorJSON[] = "42"; @@ -734,7 +729,7 @@ TEST(GeckoProfiler, Markers) "NetworkMarkerPayload stop marker", OTHER, NetworkMarkerPayload, (12, "http://mozilla.org/", NetworkLoadType::LOAD_STOP, ts1, ts2, 34, 56, net::kCacheUnresolved, 78, nullptr, nullptr, nullptr, - Some(nsDependentCString(NS_LITERAL_CSTRING("text/html").get())))); + Some(nsDependentCString("text/html")))); PROFILER_ADD_MARKER_WITH_PAYLOAD( "NetworkMarkerPayload redirect marker", OTHER, NetworkMarkerPayload, @@ -744,30 +739,28 @@ TEST(GeckoProfiler, Markers) PROFILER_ADD_MARKER_WITH_PAYLOAD( "PrefMarkerPayload marker", OTHER, PrefMarkerPayload, ("preference name", mozilla::Nothing(), mozilla::Nothing(), - NS_LITERAL_CSTRING("preference value"), ts1)); + "preference value"_ns, ts1)); - nsCString screenshotURL = NS_LITERAL_CSTRING("url"); + nsCString screenshotURL = "url"_ns; PROFILER_ADD_MARKER_WITH_PAYLOAD( "ScreenshotPayload marker", OTHER, ScreenshotPayload, (ts1, std::move(screenshotURL), mozilla::gfx::IntSize(12, 34), uintptr_t(0x45678u))); PROFILER_ADD_MARKER_WITH_PAYLOAD("TextMarkerPayload marker 1", OTHER, - TextMarkerPayload, - (NS_LITERAL_CSTRING("text"), ts1)); + TextMarkerPayload, ("text"_ns, ts1)); PROFILER_ADD_MARKER_WITH_PAYLOAD("TextMarkerPayload marker 2", OTHER, - TextMarkerPayload, - (NS_LITERAL_CSTRING("text"), ts1, ts2)); + TextMarkerPayload, ("text"_ns, ts1, ts2)); - PROFILER_ADD_MARKER_WITH_PAYLOAD( - "UserTimingMarkerPayload marker mark", OTHER, UserTimingMarkerPayload, - (NS_LITERAL_STRING("mark name"), ts1, mozilla::Nothing())); + PROFILER_ADD_MARKER_WITH_PAYLOAD("UserTimingMarkerPayload marker mark", OTHER, + UserTimingMarkerPayload, + (u"mark name"_ns, ts1, mozilla::Nothing())); PROFILER_ADD_MARKER_WITH_PAYLOAD( "UserTimingMarkerPayload marker measure", OTHER, UserTimingMarkerPayload, - (NS_LITERAL_STRING("measure name"), Some(NS_LITERAL_STRING("start mark")), - Some(NS_LITERAL_STRING("end mark")), ts1, ts2, mozilla::Nothing())); + (u"measure name"_ns, Some(u"start mark"_ns), Some(u"end mark"_ns), ts1, + ts2, mozilla::Nothing())); PROFILER_ADD_MARKER_WITH_PAYLOAD("VsyncMarkerPayload marker", OTHER, VsyncMarkerPayload, (ts1)); diff --git a/uriloader/base/nsURILoader.cpp b/uriloader/base/nsURILoader.cpp index f4b9357f355c..eb6b47766df5 100644 --- a/uriloader/base/nsURILoader.cpp +++ b/uriloader/base/nsURILoader.cpp @@ -251,7 +251,7 @@ nsresult nsDocumentOpenInfo::DispatchContent(nsIRequest* request, // Reset to application/octet-stream for now; no one other than the // external helper app service should see APPLICATION_GUESS_FROM_EXT. mContentType = APPLICATION_OCTET_STREAM; - aChannel->SetContentType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM)); + aChannel->SetContentType(nsLiteralCString(APPLICATION_OCTET_STREAM)); } // Check whether the data should be forced to be handled externally. This @@ -427,7 +427,7 @@ nsresult nsDocumentOpenInfo::DispatchContent(nsIRequest* request, if (isGuessFromExt) { mContentType = APPLICATION_GUESS_FROM_EXT; - aChannel->SetContentType(NS_LITERAL_CSTRING(APPLICATION_GUESS_FROM_EXT)); + aChannel->SetContentType(nsLiteralCString(APPLICATION_GUESS_FROM_EXT)); } rv = TryExternalHelperApp(helperAppService, aChannel); diff --git a/uriloader/exthandler/ExternalHelperAppParent.cpp b/uriloader/exthandler/ExternalHelperAppParent.cpp index 584d0f7e6271..34cda192ae73 100644 --- a/uriloader/exthandler/ExternalHelperAppParent.cpp +++ b/uriloader/exthandler/ExternalHelperAppParent.cpp @@ -76,8 +76,7 @@ void ExternalHelperAppParent::Init( NS_ASSERTION(helperAppService, "No Helper App Service!"); if (aReferrer) { - SetPropertyAsInterface(NS_LITERAL_STRING("docshell.internalReferrer"), - aReferrer); + SetPropertyAsInterface(u"docshell.internalReferrer"_ns, aReferrer); } if (aContext) { diff --git a/uriloader/exthandler/android/nsOSHelperAppService.cpp b/uriloader/exthandler/android/nsOSHelperAppService.cpp index bc3e0e4f6803..9849b660755a 100644 --- a/uriloader/exthandler/android/nsOSHelperAppService.cpp +++ b/uriloader/exthandler/android/nsOSHelperAppService.cpp @@ -37,8 +37,8 @@ nsresult nsOSHelperAppService::OSProtocolHandlerExists(const char* aScheme, // Support any URI barring a couple schemes we use in testing; let the // app decide what to do with them. nsAutoCString scheme(aScheme); - *aExists = !scheme.Equals(NS_LITERAL_CSTRING("unsupported")) && - !scheme.Equals(NS_LITERAL_CSTRING("unknownextproto")); + *aExists = + !scheme.Equals("unsupported"_ns) && !scheme.Equals("unknownextproto"_ns); return NS_OK; } diff --git a/uriloader/exthandler/mac/nsOSHelperAppService.mm b/uriloader/exthandler/mac/nsOSHelperAppService.mm index ab1013bf431a..5585fb67d296 100644 --- a/uriloader/exthandler/mac/nsOSHelperAppService.mm +++ b/uriloader/exthandler/mac/nsOSHelperAppService.mm @@ -475,7 +475,7 @@ static CFArrayRef GetMIMETypesHandledByApp(FSRef* aAppRef) { } } else { // Otherwise set the MIME type to a reasonable fallback. - mimeInfoMac->SetMIMEType(NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM)); + mimeInfoMac->SetMIMEType(nsLiteralCString(APPLICATION_OCTET_STREAM)); } } diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp index 9440f4009fc8..44e6b6e08f03 100644 --- a/uriloader/exthandler/nsExternalHelperAppService.cpp +++ b/uriloader/exthandler/nsExternalHelperAppService.cpp @@ -635,7 +635,7 @@ nsresult nsExternalHelperAppService::DoContentContentProcessHelper( // Determine whether a new window was opened specifically for this request bool shouldCloseWindow = false; if (props) { - props->GetPropertyAsBool(NS_LITERAL_STRING("docshell.newWindowTarget"), + props->GetPropertyAsBool(u"docshell.newWindowTarget"_ns, &shouldCloseWindow); } @@ -749,7 +749,7 @@ NS_IMETHODIMP nsExternalHelperAppService::CreateListener( if (fileExtension.IsEmpty() || mimeType.IsEmpty()) { // Extension lookup gave us no useful match mimeSvc->GetFromTypeAndExtension( - NS_LITERAL_CSTRING(APPLICATION_OCTET_STREAM), fileExtension, + nsLiteralCString(APPLICATION_OCTET_STREAM), fileExtension, getter_AddRefs(mimeInfo)); mimeType.AssignLiteral(APPLICATION_OCTET_STREAM); } @@ -1454,7 +1454,7 @@ nsresult nsExternalAppHandler::SetUpTempFile(nsIChannel* aChannel) { rv = mTempFile->GetLeafName(mTempLeafName); NS_ENSURE_SUCCESS(rv, rv); - NS_ENSURE_TRUE(StringEndsWith(mTempLeafName, NS_LITERAL_STRING(".part")), + NS_ENSURE_TRUE(StringEndsWith(mTempLeafName, u".part"_ns), NS_ERROR_UNEXPECTED); // Strip off the ".part" from mTempLeafName @@ -1582,8 +1582,8 @@ NS_IMETHODIMP nsExternalAppHandler::OnStartRequest(nsIRequest* request) { // Determine whether a new window was opened specifically for this request if (props) { bool tmp = false; - if (NS_SUCCEEDED(props->GetPropertyAsBool( - NS_LITERAL_STRING("docshell.newWindowTarget"), &tmp))) { + if (NS_SUCCEEDED( + props->GetPropertyAsBool(u"docshell.newWindowTarget"_ns, &tmp))) { mMaybeCloseWindowHelper->SetShouldCloseWindow(tmp); } } diff --git a/uriloader/exthandler/nsMIMEInfoImpl.cpp b/uriloader/exthandler/nsMIMEInfoImpl.cpp index 13dce65a8d11..3800d41d575f 100644 --- a/uriloader/exthandler/nsMIMEInfoImpl.cpp +++ b/uriloader/exthandler/nsMIMEInfoImpl.cpp @@ -26,7 +26,7 @@ static already_AddRefed GetCanonicalExecutable(nsIFile* aFile) { if (binary) { binary->GetLeafName(leafName); } - while (binary && !StringEndsWith(leafName, NS_LITERAL_STRING(".app"))) { + while (binary && !StringEndsWith(leafName, u".app"_ns)) { nsCOMPtr parent; binary->GetParent(getter_AddRefs(parent)); binary = parent; diff --git a/uriloader/exthandler/unix/nsOSHelperAppService.cpp b/uriloader/exthandler/unix/nsOSHelperAppService.cpp index 65ddc7d20237..9d0a2678a058 100644 --- a/uriloader/exthandler/unix/nsOSHelperAppService.cpp +++ b/uriloader/exthandler/unix/nsOSHelperAppService.cpp @@ -222,10 +222,9 @@ nsresult nsOSHelperAppService::LookUpTypeAndDescription( inline bool IsNetscapeFormat(const nsACString& aBuffer) { return StringBeginsWith( aBuffer, - NS_LITERAL_CSTRING( + nsLiteralCString( "#--Netscape Communications Corporation MIME Information")) || - StringBeginsWith(aBuffer, - NS_LITERAL_CSTRING("#--MCOM MIME Information")); + StringBeginsWith(aBuffer, "#--MCOM MIME Information"_ns); } /* @@ -568,7 +567,7 @@ nsresult nsOSHelperAppService::ParseNetscapeMIMETypesEntry( // Get the major and minor types // First the major type - if (!FindInReadable(NS_LITERAL_STRING("type="), match_start, match_end)) { + if (!FindInReadable(u"type="_ns, match_start, match_end)) { return NS_ERROR_FAILURE; } @@ -608,7 +607,7 @@ nsresult nsOSHelperAppService::ParseNetscapeMIMETypesEntry( // get the extensions match_start = match_end; match_end = end_iter; - if (FindInReadable(NS_LITERAL_STRING("exts="), match_start, match_end)) { + if (FindInReadable(u"exts="_ns, match_start, match_end)) { nsAString::const_iterator extStart, extEnd; if (match_end == end_iter || @@ -619,7 +618,7 @@ nsresult nsOSHelperAppService::ParseNetscapeMIMETypesEntry( extStart = match_end; match_start = extStart; match_end = end_iter; - if (FindInReadable(NS_LITERAL_STRING("desc=\""), match_start, match_end)) { + if (FindInReadable(u"desc=\""_ns, match_start, match_end)) { // exts= before desc=, so we have to find the actual end of the extensions extEnd = match_start; if (extEnd == extStart) { @@ -646,11 +645,11 @@ nsresult nsOSHelperAppService::ParseNetscapeMIMETypesEntry( // get the description match_start = start_iter; match_end = end_iter; - if (FindInReadable(NS_LITERAL_STRING("desc=\""), match_start, match_end)) { + if (FindInReadable(u"desc=\""_ns, match_start, match_end)) { aDescriptionStart = match_end; match_start = aDescriptionStart; match_end = end_iter; - if (FindInReadable(NS_LITERAL_STRING("exts="), match_start, match_end)) { + if (FindInReadable(u"exts="_ns, match_start, match_end)) { // exts= after desc=, so have to find actual end of description aDescriptionEnd = match_start; if (aDescriptionEnd == aDescriptionStart) { @@ -777,15 +776,13 @@ nsresult nsOSHelperAppService::LookUpHandlerAndDescription( // maybe we have an entry for "aMajorType/*"? if (NS_FAILED(rv)) { - rv = DoLookUpHandlerAndDescription(aMajorType, NS_LITERAL_STRING("*"), - aHandler, aDescription, aMozillaFlags, - true); + rv = DoLookUpHandlerAndDescription(aMajorType, u"*"_ns, aHandler, + aDescription, aMozillaFlags, true); } if (NS_FAILED(rv)) { - rv = DoLookUpHandlerAndDescription(aMajorType, NS_LITERAL_STRING("*"), - aHandler, aDescription, aMozillaFlags, - false); + rv = DoLookUpHandlerAndDescription(aMajorType, u"*"_ns, aHandler, + aDescription, aMozillaFlags, false); } return rv; @@ -970,7 +967,7 @@ nsresult nsOSHelperAppService::GetHandlerAndDescriptionFromMailcapFile( nsCOMPtr file( do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv)); if (NS_FAILED(rv)) continue; - rv = file->InitWithNativePath(NS_LITERAL_CSTRING("/bin/sh")); + rv = file->InitWithNativePath("/bin/sh"_ns); if (NS_FAILED(rv)) continue; rv = process->Init(file); if (NS_FAILED(rv)) continue; @@ -1171,8 +1168,7 @@ already_AddRefed nsOSHelperAppService::GetFromExtension( return nullptr; } - nsAutoCString mimeType(asciiMajorType + NS_LITERAL_CSTRING("/") + - asciiMinorType); + nsAutoCString mimeType(asciiMajorType + "/"_ns + asciiMinorType); RefPtr mimeInfo = new nsMIMEInfoUnix(mimeType); mimeInfo->AppendExtension(aFileExt); @@ -1276,12 +1272,12 @@ already_AddRefed nsOSHelperAppService::GetFromType( } if (handler.IsEmpty()) { - DoLookUpHandlerAndDescription(majorType, NS_LITERAL_STRING("*"), handler, + DoLookUpHandlerAndDescription(majorType, u"*"_ns, handler, mailcap_description, mozillaFlags, true); } if (handler.IsEmpty()) { - DoLookUpHandlerAndDescription(majorType, NS_LITERAL_STRING("*"), handler, + DoLookUpHandlerAndDescription(majorType, u"*"_ns, handler, mailcap_description, mozillaFlags, false); } diff --git a/uriloader/exthandler/win/nsMIMEInfoWin.cpp b/uriloader/exthandler/win/nsMIMEInfoWin.cpp index a6e187005d99..1ea2a3268068 100644 --- a/uriloader/exthandler/win/nsMIMEInfoWin.cpp +++ b/uriloader/exthandler/win/nsMIMEInfoWin.cpp @@ -220,12 +220,10 @@ nsMIMEInfoWin::GetEnumerator(nsISimpleEnumerator** _retval) { nsCOMArray properties; nsCOMPtr variant; - GetProperty(NS_LITERAL_STRING("defaultApplicationIconURL"), - getter_AddRefs(variant)); + GetProperty(u"defaultApplicationIconURL"_ns, getter_AddRefs(variant)); if (variant) properties.AppendObject(variant); - GetProperty(NS_LITERAL_STRING("customApplicationIconURL"), - getter_AddRefs(variant)); + GetProperty(u"customApplicationIconURL"_ns, getter_AddRefs(variant)); if (variant) properties.AppendObject(variant); return NS_NewArrayEnumerator(_retval, properties, NS_GET_IID(nsIVariant)); @@ -291,8 +289,8 @@ nsresult nsMIMEInfoWin::LoadUriInternal(nsIURI* aURL) { do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); - if (NS_FAILED(textToSubURI->UnEscapeNonAsciiURI(NS_LITERAL_CSTRING("UTF-8"), - urlSpec, utf16Spec))) { + if (NS_FAILED(textToSubURI->UnEscapeNonAsciiURI("UTF-8"_ns, urlSpec, + utf16Spec))) { CopyASCIItoUTF16(urlSpec, utf16Spec); } @@ -382,14 +380,12 @@ bool nsMIMEInfoWin::GetAppsVerbCommandHandler(const nsAString& appExeName, // Check for the NoOpenWith flag, if it exists uint32_t value; - if (NS_SUCCEEDED( - appKey->ReadIntValue(NS_LITERAL_STRING("NoOpenWith"), &value)) && + if (NS_SUCCEEDED(appKey->ReadIntValue(u"NoOpenWith"_ns, &value)) && value == 1) return false; nsAutoString dummy; - if (NS_SUCCEEDED( - appKey->ReadStringValue(NS_LITERAL_STRING("NoOpenWith"), dummy))) + if (NS_SUCCEEDED(appKey->ReadStringValue(u"NoOpenWith"_ns, dummy))) return false; appKey->Close(); @@ -445,12 +441,11 @@ bool nsMIMEInfoWin::GetDllLaunchInfo(nsIFile* aDll, nsIFile* aFile, // Check for the NoOpenWith flag, if it exists uint32_t value; - rv = appKey->ReadIntValue(NS_LITERAL_STRING("NoOpenWith"), &value); + rv = appKey->ReadIntValue(u"NoOpenWith"_ns, &value); if (NS_SUCCEEDED(rv) && value == 1) return false; nsAutoString dummy; - if (NS_SUCCEEDED( - appKey->ReadStringValue(NS_LITERAL_STRING("NoOpenWith"), dummy))) + if (NS_SUCCEEDED(appKey->ReadStringValue(u"NoOpenWith"_ns, dummy))) return false; appKey->Close(); @@ -664,7 +659,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { nsAutoString appProgId; if (NS_SUCCEEDED(regKey->ReadStringValue(EmptyString(), appProgId))) { // Bug 358297 - ignore the embedded internet explorer handler - if (appProgId != NS_LITERAL_STRING("XPSViewer.Document")) { + if (appProgId != u"XPSViewer.Document"_ns) { nsAutoString appFilesystemCommand; if (GetProgIDVerbCommandHandler(appProgId, appFilesystemCommand, false) && @@ -735,8 +730,8 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion // \Explorer\FileExts\.ext\OpenWithList - workingRegistryPath = NS_LITERAL_STRING( - "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); + workingRegistryPath = nsLiteralString( + u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); workingRegistryPath += fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithList"); @@ -768,8 +763,8 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { // HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion // \Explorer\FileExts\.ext\OpenWithProgids - workingRegistryPath = NS_LITERAL_STRING( - "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); + workingRegistryPath = nsLiteralString( + u"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\"); workingRegistryPath += fileExtToUse; workingRegistryPath.AppendLiteral("\\OpenWithProgids"); @@ -803,11 +798,9 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) { nsAutoString perceivedType; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("PerceivedType"), - perceivedType); + rv = regKey->ReadStringValue(u"PerceivedType"_ns, perceivedType); if (NS_SUCCEEDED(rv)) { - nsAutoString openWithListPath( - NS_LITERAL_STRING("SystemFileAssociations\\")); + nsAutoString openWithListPath(u"SystemFileAssociations\\"_ns); openWithListPath.Append(perceivedType); // no period openWithListPath.AppendLiteral("\\OpenWithList"); @@ -839,7 +832,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { // Listing general purpose handlers, not specific to a mime type or file // extension - workingRegistryPath = NS_LITERAL_STRING("*\\OpenWithList"); + workingRegistryPath = u"*\\OpenWithList"_ns; rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, nsIWindowsRegKey::ACCESS_QUERY_VALUE); @@ -862,7 +855,7 @@ nsMIMEInfoWin::GetPossibleLocalHandlers(nsIArray** _retval) { } // 8) General application's list - not file extension specific on windows - workingRegistryPath = NS_LITERAL_STRING("Applications"); + workingRegistryPath = u"Applications"_ns; rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, workingRegistryPath, diff --git a/uriloader/exthandler/win/nsOSHelperAppService.cpp b/uriloader/exthandler/win/nsOSHelperAppService.cpp index da5459747c8b..aa330ca05bdd 100644 --- a/uriloader/exthandler/win/nsOSHelperAppService.cpp +++ b/uriloader/exthandler/win/nsOSHelperAppService.cpp @@ -63,7 +63,7 @@ static nsresult GetExtensionFromWindowsMimeDatabase(const nsACString& aMimeType, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_SUCCEEDED(rv)) - regKey->ReadStringValue(NS_LITERAL_STRING("Extension"), aFileExtension); + regKey->ReadStringValue(u"Extension"_ns, aFileExtension); return NS_OK; } @@ -97,7 +97,7 @@ nsresult nsOSHelperAppService::OSProtocolHandlerExists( } bool hasValue; - rv = regKey->HasValue(NS_LITERAL_STRING("URL Protocol"), &hasValue); + rv = regKey->HasValue(u"URL Protocol"_ns, &hasValue); if (NS_FAILED(rv)) { return NS_ERROR_FAILURE; } @@ -242,7 +242,7 @@ bool nsOSHelperAppService::typeFromExtEquals(const char16_t* aExt, if (NS_FAILED(rv)) return eq; nsAutoString type; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("Content Type"), type); + rv = regKey->ReadStringValue(u"Content Type"_ns, type); if (NS_SUCCEEDED(rv)) eq = type.EqualsASCII(aType); return eq; @@ -298,8 +298,7 @@ nsresult nsOSHelperAppService::GetDefaultAppInfo( if (NS_FAILED(rv)) { // Check if there is a DelegateExecute string nsAutoString delegateExecute; - rv = regKey->ReadStringValue(NS_LITERAL_STRING("DelegateExecute"), - delegateExecute); + rv = regKey->ReadStringValue(u"DelegateExecute"_ns, delegateExecute); NS_ENSURE_SUCCESS(rv, rv); // Look for InProcServer32 @@ -577,8 +576,7 @@ bool nsOSHelperAppService::GetMIMETypeFromOSForExtension( if (NS_FAILED(rv)) return false; nsAutoString mimeType; - if (NS_FAILED(regKey->ReadStringValue(NS_LITERAL_STRING("Content Type"), - mimeType)) || + if (NS_FAILED(regKey->ReadStringValue(u"Content Type"_ns, mimeType)) || mimeType.IsEmpty()) { return false; } diff --git a/uriloader/prefetch/nsOfflineCacheUpdate.cpp b/uriloader/prefetch/nsOfflineCacheUpdate.cpp index 3dc315542fc7..100ba6e6f77b 100644 --- a/uriloader/prefetch/nsOfflineCacheUpdate.cpp +++ b/uriloader/prefetch/nsOfflineCacheUpdate.cpp @@ -163,9 +163,8 @@ nsresult nsManifestCheck::Begin() { new mozilla::dom::ReferrerInfo(mReferrerURI); rv = httpChannel->SetReferrerInfoWithoutClone(referrerInfo); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"), - NS_LITERAL_CSTRING("offline-resource"), - false); + rv = + httpChannel->SetRequestHeader("X-Moz"_ns, "offline-resource"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -344,9 +343,8 @@ nsresult nsOfflineCacheUpdateItem::OpenChannel(nsOfflineCacheUpdate* aUpdate) { new mozilla::dom::ReferrerInfo(mReferrerURI); rv = httpChannel->SetReferrerInfoWithoutClone(referrerInfo); MOZ_ASSERT(NS_SUCCEEDED(rv)); - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"), - NS_LITERAL_CSTRING("offline-resource"), - false); + rv = + httpChannel->SetRequestHeader("X-Moz"_ns, "offline-resource"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); } @@ -509,9 +507,7 @@ nsOfflineCacheUpdateItem::AsyncOnChannelRedirect( nsCOMPtr httpChannel = do_QueryInterface(aNewChannel); NS_ENSURE_STATE(httpChannel); - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"), - NS_LITERAL_CSTRING("offline-resource"), - false); + rv = httpChannel->SetRequestHeader("X-Moz"_ns, "offline-resource"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); mChannel = aNewChannel; diff --git a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp index 6daa8d4d8baf..3f43193e39de 100644 --- a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp +++ b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp @@ -553,8 +553,7 @@ static nsresult OfflineAppPermForPrincipal(nsIPrincipal* aPrincipal, } uint32_t perm; - const nsLiteralCString permName = pinned ? NS_LITERAL_CSTRING("pin-app") - : NS_LITERAL_CSTRING("offline-app"); + const nsLiteralCString permName = pinned ? "pin-app"_ns : "offline-app"_ns; permissionManager->TestExactPermissionFromPrincipal(aPrincipal, permName, &perm); @@ -638,9 +637,8 @@ nsOfflineCacheUpdateService::AllowOfflineApp(nsIPrincipal* aPrincipal) { if (!permissionManager) return NS_ERROR_NOT_AVAILABLE; rv = permissionManager->AddFromPrincipal( - aPrincipal, NS_LITERAL_CSTRING("offline-app"), - nsIPermissionManager::ALLOW_ACTION, nsIPermissionManager::EXPIRE_NEVER, - 0); + aPrincipal, "offline-app"_ns, nsIPermissionManager::ALLOW_ACTION, + nsIPermissionManager::EXPIRE_NEVER, 0); NS_ENSURE_SUCCESS(rv, rv); } diff --git a/uriloader/prefetch/nsPrefetchService.cpp b/uriloader/prefetch/nsPrefetchService.cpp index 0d75045970f6..0c03827ad8a3 100644 --- a/uriloader/prefetch/nsPrefetchService.cpp +++ b/uriloader/prefetch/nsPrefetchService.cpp @@ -128,8 +128,7 @@ nsresult nsPrefetchNode::OpenChannel() { if (httpChannel) { DebugOnly success = httpChannel->SetReferrerInfo(mReferrerInfo); MOZ_ASSERT(NS_SUCCEEDED(success)); - success = httpChannel->SetRequestHeader( - NS_LITERAL_CSTRING("X-Moz"), NS_LITERAL_CSTRING("prefetch"), false); + success = httpChannel->SetRequestHeader("X-Moz"_ns, "prefetch"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(success)); } @@ -289,8 +288,7 @@ nsPrefetchNode::AsyncOnChannelRedirect( nsCOMPtr httpChannel = do_QueryInterface(aNewChannel); NS_ENSURE_STATE(httpChannel); - rv = httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"), - NS_LITERAL_CSTRING("prefetch"), false); + rv = httpChannel->SetRequestHeader("X-Moz"_ns, "prefetch"_ns, false); MOZ_ASSERT(NS_SUCCEEDED(rv)); // Assign to mChannel after we get notification about success of the @@ -440,9 +438,7 @@ void nsPrefetchService::DispatchEvent(nsPrefetchNode* node, bool aSuccess) { // that we're not allowed to touch. (Our network request happens in the // DocGroup of one of the mSources nodes--not necessarily this one). RefPtr dispatcher = new AsyncEventDispatcher( - domNode, - aSuccess ? NS_LITERAL_STRING("load") : NS_LITERAL_STRING("error"), - CanBubble::eNo); + domNode, aSuccess ? u"load"_ns : u"error"_ns, CanBubble::eNo); dispatcher->RequireNodeInDocument(); dispatcher->PostDOMEvent(); } diff --git a/uriloader/preload/FetchPreloader.cpp b/uriloader/preload/FetchPreloader.cpp index 0439167376ed..fdfd123801a9 100644 --- a/uriloader/preload/FetchPreloader.cpp +++ b/uriloader/preload/FetchPreloader.cpp @@ -111,7 +111,7 @@ nsresult FetchPreloader::CreateChannel( } if (nsCOMPtr timedChannel = do_QueryInterface(channel)) { - timedChannel->SetInitiatorType(NS_LITERAL_STRING("link")); + timedChannel->SetInitiatorType(u"link"_ns); } channel.forget(aChannel); diff --git a/uriloader/preload/PreloadService.cpp b/uriloader/preload/PreloadService.cpp index f5850eb8d56e..b121cfd57121 100644 --- a/uriloader/preload/PreloadService.cpp +++ b/uriloader/preload/PreloadService.cpp @@ -245,8 +245,7 @@ void PreloadService::NotifyNodeEvent(nsINode* aNode, bool aSuccess) { // DocGroup of one of the mSources nodes--not necessarily this one). RefPtr dispatcher = new AsyncEventDispatcher( - aNode, aSuccess ? NS_LITERAL_STRING("load") : NS_LITERAL_STRING("error"), - CanBubble::eNo); + aNode, aSuccess ? u"load"_ns : u"error"_ns, CanBubble::eNo); dispatcher->RequireNodeInDocument(); dispatcher->PostDOMEvent(); diff --git a/uriloader/preload/PreloaderBase.cpp b/uriloader/preload/PreloaderBase.cpp index 034128f5684c..58021765c44a 100644 --- a/uriloader/preload/PreloaderBase.cpp +++ b/uriloader/preload/PreloaderBase.cpp @@ -312,10 +312,10 @@ NS_IMETHODIMP PreloaderBase::UsageTimer::Notify(nsITimer* aTimer) { } nsString spec = NS_ConvertUTF8toUTF16(uri->GetSpecOrDefault()); - nsContentUtils::ReportToConsole( - nsIScriptError::warningFlag, NS_LITERAL_CSTRING("DOM"), mDocument, - nsContentUtils::eDOM_PROPERTIES, "UnusedLinkPreloadPending", - nsTArray({spec})); + nsContentUtils::ReportToConsole(nsIScriptError::warningFlag, "DOM"_ns, + mDocument, nsContentUtils::eDOM_PROPERTIES, + "UnusedLinkPreloadPending", + nsTArray({spec})); return NS_OK; } diff --git a/uriloader/preload/gtest/TestFetchPreloader.cpp b/uriloader/preload/gtest/TestFetchPreloader.cpp index 0290aa9339b4..1531ef471a7c 100644 --- a/uriloader/preload/gtest/TestFetchPreloader.cpp +++ b/uriloader/preload/gtest/TestFetchPreloader.cpp @@ -263,7 +263,7 @@ void Yield() { eventInProgress = false; } TEST(TestFetchPreloader, CacheNoneBeforeConsume) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -280,9 +280,9 @@ TEST(TestFetchPreloader, CacheNoneBeforeConsume) EXPECT_FALSE(NS_SUCCEEDED(preloader->AsyncConsume(listener))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { @@ -301,7 +301,7 @@ TEST(TestFetchPreloader, CacheNoneBeforeConsume) TEST(TestFetchPreloader, CacheStartBeforeConsume) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -322,9 +322,9 @@ TEST(TestFetchPreloader, CacheStartBeforeConsume) NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { EXPECT_TRUE(listener->mOnStart); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(listener->mOnData.EqualsLiteral("onetwothree")); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); @@ -341,7 +341,7 @@ TEST(TestFetchPreloader, CacheStartBeforeConsume) TEST(TestFetchPreloader, CachePartOfDataBeforeConsume) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -354,8 +354,8 @@ TEST(TestFetchPreloader, CachePartOfDataBeforeConsume) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); RefPtr listener = new FakeListener(); EXPECT_TRUE(NS_SUCCEEDED(preloader->AsyncConsume(listener))); @@ -364,7 +364,7 @@ TEST(TestFetchPreloader, CachePartOfDataBeforeConsume) NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { EXPECT_TRUE(listener->mOnStart); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(listener->mOnData.EqualsLiteral("onetwothree")); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); @@ -381,7 +381,7 @@ TEST(TestFetchPreloader, CachePartOfDataBeforeConsume) TEST(TestFetchPreloader, CacheAllDataBeforeConsume) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -394,9 +394,9 @@ TEST(TestFetchPreloader, CacheAllDataBeforeConsume) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); // Request consumation of the preload... RefPtr listener = new FakeListener(); @@ -421,7 +421,7 @@ TEST(TestFetchPreloader, CacheAllDataBeforeConsume) TEST(TestFetchPreloader, CacheAllBeforeConsume) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -434,9 +434,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsume) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -460,7 +460,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsume) TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelError) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -473,9 +473,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelError) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_FAILED(channel->Stop(ERROR_ONSTOP))); RefPtr listener = new FakeListener(); @@ -499,7 +499,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelError) TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelCancel) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -512,8 +512,8 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelCancel) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); channel->Cancel(ERROR_CANCEL); EXPECT_TRUE(NS_FAILED(channel->Stop(ERROR_CANCEL))); @@ -542,7 +542,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeWithChannelCancel) TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStartRequest) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -555,9 +555,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStartRequest) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -582,7 +582,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStartRequest) TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnDataAvailable) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -595,9 +595,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnDataAvailable) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -622,7 +622,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnDataAvailable) TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStopRequest) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -635,9 +635,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStopRequest) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -664,7 +664,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeThrowFromOnStopRequest) TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnStartRequest) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -677,9 +677,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnStartRequest) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -707,7 +707,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnStartRequest) TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnDataAvailable) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -720,9 +720,9 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnDataAvailable) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); RefPtr listener = new FakeListener(); @@ -751,7 +751,7 @@ TEST(TestFetchPreloader, CacheAllBeforeConsumeCancelInOnDataAvailable) TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailable) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -764,8 +764,8 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailable) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); RefPtr listener = new FakeListener(); listener->mCancelIn = FakeListener::OnData; @@ -774,7 +774,7 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailable) EXPECT_FALSE(NS_SUCCEEDED(preloader->AsyncConsume(listener))); NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { - EXPECT_TRUE(NS_FAILED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_FAILED(channel->Data("three"_ns))); EXPECT_TRUE(NS_FAILED(channel->Stop(NS_OK))); EXPECT_TRUE(listener->mOnStart); @@ -792,7 +792,7 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailable) TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnStartRequestAndRace) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -805,14 +805,14 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnStartRequestAndRace) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); // This has to simulate a possibiilty when stream listener notifications from // the channel are already pending in the queue while AsyncConsume is called. // At this moment the listener has not been notified yet. NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); })); @@ -841,7 +841,7 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnStartRequestAndRace) TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailableAndRace) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -854,14 +854,14 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailableAndRace) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); // This has to simulate a possibiilty when stream listener notifications from // the channel are already pending in the queue while AsyncConsume is called. // At this moment the listener has not been notified yet. NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); })); @@ -890,7 +890,7 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeCancelInOnDataAvailableAndRace) TEST(TestFetchPreloader, CachePartlyBeforeConsumeThrowFromOnStartRequestAndRace) { nsCOMPtr uri; - NS_NewURI(getter_AddRefs(uri), NS_LITERAL_CSTRING("https://example.com")); + NS_NewURI(getter_AddRefs(uri), "https://example.com"_ns); auto key = mozilla::PreloadHashKey::CreateAsFetch(uri, mozilla::CORS_NONE); RefPtr channel = new FakeChannel(); @@ -903,14 +903,14 @@ TEST(TestFetchPreloader, CachePartlyBeforeConsumeThrowFromOnStartRequestAndRace) mozilla::dom::ReferrerPolicy::_empty, doc))); EXPECT_TRUE(NS_SUCCEEDED(channel->Start())); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("one")))); - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("two")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("one"_ns))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("two"_ns))); // This has to simulate a possibiilty when stream listener notifications from // the channel are already pending in the queue while AsyncConsume is called. // At this moment the listener has not been notified yet. NS_DispatchToMainThread(NS_NewRunnableFunction("test", [&]() { - EXPECT_TRUE(NS_SUCCEEDED(channel->Data(NS_LITERAL_CSTRING("three")))); + EXPECT_TRUE(NS_SUCCEEDED(channel->Data("three"_ns))); EXPECT_TRUE(NS_SUCCEEDED(channel->Stop(NS_OK))); })); diff --git a/widget/GfxInfoBase.cpp b/widget/GfxInfoBase.cpp index 4b070c4e346f..28c8c3a30b0e 100644 --- a/widget/GfxInfoBase.cpp +++ b/widget/GfxInfoBase.cpp @@ -487,8 +487,7 @@ static bool BlocklistEntryToDriverInfo(nsCString& aBlocklistEntry, nsTArray keyValues; ParseString(aBlocklistEntry, '\t', keyValues); - aDriverInfo.mRuleId = - NS_LITERAL_CSTRING("FEATURE_FAILURE_DL_BLOCKLIST_NO_ID"); + aDriverInfo.mRuleId = "FEATURE_FAILURE_DL_BLOCKLIST_NO_ID"_ns; for (uint32_t i = 0; i < keyValues.Length(); ++i) { nsCString keyValue = keyValues[i]; @@ -512,8 +511,7 @@ static bool BlocklistEntryToDriverInfo(nsCString& aBlocklistEntry, } if (key.EqualsLiteral("blockID")) { - nsCString blockIdStr = - NS_LITERAL_CSTRING("FEATURE_FAILURE_DL_BLOCKLIST_") + value; + nsCString blockIdStr = "FEATURE_FAILURE_DL_BLOCKLIST_"_ns + value; aDriverInfo.mRuleId = blockIdStr.get(); } else if (key.EqualsLiteral("os")) { aDriverInfo.mOperatingSystem = BlocklistOSToOperatingSystem(dataValue); @@ -1059,7 +1057,7 @@ int32_t GfxInfoBase::FindBlocklistedDeviceInList( if (!adapterInfoFailed[1]) { nsAString& nvVendorID = (nsAString&)GfxDriverInfo::GetDeviceVendor(DeviceVendor::NVIDIA); - const nsString nv310mDeviceId = NS_LITERAL_STRING("0x0A70"); + const nsString nv310mDeviceId = u"0x0A70"_ns; if (nvVendorID.Equals(adapterVendorID[1], nsCaseInsensitiveStringComparator) && nv310mDeviceId.Equals(adapterDeviceID[1], @@ -1623,7 +1621,8 @@ void GfxInfoBase::DescribeFeatures(JSContext* aCx, JS::Handle aObj) { gfx::FeatureState& webrender = gfxConfig::GetFeature(gfx::Feature::WEBRENDER); InitFeatureObject(aCx, aObj, "webrender", webrender, &obj); - gfx::FeatureState& wrCompositor = gfxConfig::GetFeature(gfx::Feature::WEBRENDER_COMPOSITOR); + gfx::FeatureState& wrCompositor = + gfxConfig::GetFeature(gfx::Feature::WEBRENDER_COMPOSITOR); InitFeatureObject(aCx, aObj, "wrCompositor", wrCompositor, &obj); gfx::FeatureState& openglCompositing = gfxConfig::GetFeature(gfx::Feature::OPENGL_COMPOSITING); diff --git a/widget/TextEventDispatcher.cpp b/widget/TextEventDispatcher.cpp index e307a1e1d150..73ee6ba8d66a 100644 --- a/widget/TextEventDispatcher.cpp +++ b/widget/TextEventDispatcher.cpp @@ -370,10 +370,8 @@ nsresult TextEventDispatcher::CommitComposition( // editor requires non-void string even when it's empty. compositionCommitEvent.mData.SetIsVoid(false); // Don't send CRLF nor CR, replace it with LF here. - compositionCommitEvent.mData.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), - NS_LITERAL_STRING("\n")); - compositionCommitEvent.mData.ReplaceSubstring(NS_LITERAL_STRING("\r"), - NS_LITERAL_STRING("\n")); + compositionCommitEvent.mData.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns); + compositionCommitEvent.mData.ReplaceSubstring(u"\r"_ns, u"\n"_ns); } rv = DispatchEvent(widget, compositionCommitEvent, aStatus); if (NS_WARN_IF(NS_FAILED(rv))) { @@ -808,8 +806,8 @@ void TextEventDispatcher::PendingComposition::ReplaceNativeLineBreakers() { nsAutoString nativeString(mString); // Don't expose CRLF nor CR to web contents, instead, use LF. - mString.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), NS_LITERAL_STRING("\n")); - mString.ReplaceSubstring(NS_LITERAL_STRING("\r"), NS_LITERAL_STRING("\n")); + mString.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns); + mString.ReplaceSubstring(u"\r"_ns, u"\n"_ns); // If the length isn't changed, we don't need to adjust any offset and length // of mClauses nor mCaret. @@ -838,8 +836,7 @@ void TextEventDispatcher::PendingComposition::AdjustRange( // composition string is usually short and separated as a few clauses. if (nativeRange.mStartOffset > 0) { nsAutoString preText(Substring(aNativeString, 0, nativeRange.mStartOffset)); - preText.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), - NS_LITERAL_STRING("\n")); + preText.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns); aRange.mStartOffset = preText.Length(); } if (nativeRange.Length() == 0) { @@ -847,7 +844,7 @@ void TextEventDispatcher::PendingComposition::AdjustRange( } else { nsAutoString clause(Substring(aNativeString, nativeRange.mStartOffset, nativeRange.Length())); - clause.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), NS_LITERAL_STRING("\n")); + clause.ReplaceSubstring(u"\r\n"_ns, u"\n"_ns); aRange.mEndOffset = aRange.mStartOffset + clause.Length(); } } diff --git a/widget/WidgetEventImpl.cpp b/widget/WidgetEventImpl.cpp index 3cd40244d468..c00850842c0a 100644 --- a/widget/WidgetEventImpl.cpp +++ b/widget/WidgetEventImpl.cpp @@ -66,7 +66,7 @@ const char* ToChar(EventClassID aEventClassID) { const nsCString ToString(KeyNameIndex aKeyNameIndex) { if (aKeyNameIndex == KEY_NAME_INDEX_USE_STRING) { - return NS_LITERAL_CSTRING("USE_STRING"); + return "USE_STRING"_ns; } nsAutoString keyName; WidgetKeyboardEvent::GetDOMKeyName(aKeyNameIndex, keyName); @@ -75,7 +75,7 @@ const nsCString ToString(KeyNameIndex aKeyNameIndex) { const nsCString ToString(CodeNameIndex aCodeNameIndex) { if (aCodeNameIndex == CODE_NAME_INDEX_USE_STRING) { - return NS_LITERAL_CSTRING("USE_STRING"); + return "USE_STRING"_ns; } nsAutoString codeName; WidgetKeyboardEvent::GetDOMCodeName(aCodeNameIndex, codeName); @@ -114,7 +114,7 @@ const nsCString GetDOMKeyCodeName(uint32_t aKeyCode) { #define NS_DISALLOW_SAME_KEYCODE #define NS_DEFINE_VK(aDOMKeyName, aDOMKeyCode) \ case aDOMKeyCode: \ - return NS_LITERAL_CSTRING(#aDOMKeyName); + return nsLiteralCString(#aDOMKeyName); #include "mozilla/VirtualKeyCodeList.h" diff --git a/widget/android/AndroidAlerts.cpp b/widget/android/AndroidAlerts.cpp index 97d3b160d42f..3689ddb2850b 100644 --- a/widget/android/AndroidAlerts.cpp +++ b/widget/android/AndroidAlerts.cpp @@ -136,7 +136,7 @@ void AndroidAlerts::NotifyListener(const nsAString& aName, const char* aTopic, listener->Observe(nullptr, aTopic, aCookie); - if (NS_LITERAL_CSTRING("alertfinished").Equals(aTopic)) { + if ("alertfinished"_ns.Equals(aTopic)) { sListenerMap->Remove(aName); mNotificationsMap.Remove(aName); } diff --git a/widget/android/EventDispatcher.cpp b/widget/android/EventDispatcher.cpp index 65579a1214c5..c9f43fa50f98 100644 --- a/widget/android/EventDispatcher.cpp +++ b/widget/android/EventDispatcher.cpp @@ -558,7 +558,7 @@ class JavaCallbackDelegate final : public nsIAndroidEventCallback { MOZ_ASSERT(NS_IsMainThread()); jni::Object::LocalRef data(jni::GetGeckoThreadEnv()); - nsresult rv = BoxData(NS_LITERAL_STRING("callback"), aCx, aData, data, + nsresult rv = BoxData(u"callback"_ns, aCx, aData, data, /* ObjectOnly */ false); NS_ENSURE_SUCCESS(rv, rv); @@ -606,8 +606,8 @@ class NativeCallbackDelegateSupport final NS_ENSURE_TRUE_VOID(jsapi.Init(mGlobalObject)); JS::RootedValue data(jsapi.cx()); - nsresult rv = UnboxData(NS_LITERAL_STRING("callback"), jsapi.cx(), aData, - &data, /* BundleOnly */ false); + nsresult rv = UnboxData(u"callback"_ns, jsapi.cx(), aData, &data, + /* BundleOnly */ false); NS_ENSURE_SUCCESS_VOID(rv); rv = (mCallback->*aCall)(data, jsapi.cx()); diff --git a/widget/android/jni/Utils.cpp b/widget/android/jni/Utils.cpp index b87585e063aa..974b46a4088c 100644 --- a/widget/android/jni/Utils.cpp +++ b/widget/android/jni/Utils.cpp @@ -230,8 +230,7 @@ bool ReportException(JNIEnv* aEnv, jthrowable aExc, jstring aStack) { aEnv->ExceptionDescribe(); aEnv->ExceptionClear(); } else if (appNotes) { - CrashReporter::AppendAppNotesToCrashReport(NS_LITERAL_CSTRING("\n") + - appNotes->ToCString()); + CrashReporter::AppendAppNotesToCrashReport("\n"_ns + appNotes->ToCString()); } if (sOOMErrorClass && aEnv->IsInstanceOf(aExc, sOOMErrorClass)) { diff --git a/widget/android/nsAppShell.cpp b/widget/android/nsAppShell.cpp index fff3b1bb5070..9bf7328bd6c4 100644 --- a/widget/android/nsAppShell.cpp +++ b/widget/android/nsAppShell.cpp @@ -355,9 +355,9 @@ class XPCOMEventTargetWrapper final static void Init() { java::XPCOMEventTarget::Natives::Init(); - CreateWrapper(NS_LITERAL_STRING("main"), do_GetMainThread()); + CreateWrapper(u"main"_ns, do_GetMainThread()); if (XRE_IsParentProcess()) { - CreateWrapper(NS_LITERAL_STRING("launcher"), ipc::GetIPCLauncher()); + CreateWrapper(u"launcher"_ns, ipc::GetIPCLauncher()); } } @@ -588,8 +588,7 @@ nsAppShell::Observe(nsISupports* aSubject, const char* aTopic, } } else if (!strcmp(aTopic, "quit-application")) { if (jni::IsAvailable()) { - const bool restarting = - aData && NS_LITERAL_STRING("restart").Equals(aData); + const bool restarting = aData && u"restart"_ns.Equals(aData); java::GeckoThread::SetState(restarting ? java::GeckoThread::State::RESTARTING() : java::GeckoThread::State::EXITING()); diff --git a/widget/android/nsPrintSettingsServiceAndroid.cpp b/widget/android/nsPrintSettingsServiceAndroid.cpp index 77ffbe745792..3abf2e4bb848 100644 --- a/widget/android/nsPrintSettingsServiceAndroid.cpp +++ b/widget/android/nsPrintSettingsServiceAndroid.cpp @@ -11,7 +11,7 @@ class nsPrintSettingsAndroid : public nsPrintSettings { nsPrintSettingsAndroid() { // The aim here is to set up the objects enough that silent printing works SetOutputFormat(nsIPrintSettings::kOutputFormatPDF); - SetPrinterName(NS_LITERAL_STRING("PDF printer")); + SetPrinterName(u"PDF printer"_ns); } }; diff --git a/widget/android/nsWindow.cpp b/widget/android/nsWindow.cpp index ae56d1686962..4d0760b745a7 100644 --- a/widget/android/nsWindow.cpp +++ b/widget/android/nsWindow.cpp @@ -1317,7 +1317,7 @@ void nsWindow::GeckoViewSupport::Open( } else { nsresult rv = Preferences::GetCString("toolkit.defaultChromeURI", url); if (NS_FAILED(rv)) { - url = NS_LITERAL_CSTRING("chrome://geckoview/content/geckoview.xhtml"); + url = "chrome://geckoview/content/geckoview.xhtml"_ns; } } diff --git a/widget/cocoa/TextInputHandler.mm b/widget/cocoa/TextInputHandler.mm index 7a0adfed0371..06a51ecd0447 100644 --- a/widget/cocoa/TextInputHandler.mm +++ b/widget/cocoa/TextInputHandler.mm @@ -4688,8 +4688,7 @@ static void EnsureToLogAllKeyboardLayoutsAndIMEs() { tis.InitByCurrentInputSource(); nsAutoString inputSourceID; tis.GetInputSourceID(inputSourceID); - allowConsumeEvent = - !StringBeginsWith(inputSourceID, NS_LITERAL_STRING("com.apple.inputmethod.Korean.")); + allowConsumeEvent = !StringBeginsWith(inputSourceID, u"com.apple.inputmethod.Korean."_ns); } NSTextInputContext* inputContext = [mView inputContext]; return [inputContext handleEvent:aEvent] && allowConsumeEvent; diff --git a/widget/cocoa/nsChildView.mm b/widget/cocoa/nsChildView.mm index bff7de810800..0cd41dcc856c 100644 --- a/widget/cocoa/nsChildView.mm +++ b/widget/cocoa/nsChildView.mm @@ -3879,8 +3879,8 @@ - (void)keyDown:(NSEvent*)theEvent { !TextInputHandler::IsSecureEventInputEnabled()) { # define CRASH_MESSAGE "A password editor has focus, but not in secure input mode" - CrashReporter::AppendAppNotesToCrashReport(NS_LITERAL_CSTRING("\nBug 893973: ") + - NS_LITERAL_CSTRING(CRASH_MESSAGE)); + CrashReporter::AppendAppNotesToCrashReport("\nBug 893973: "_ns + + nsLiteralCString(CRASH_MESSAGE)); CrashReporter::AppendAppNotesToCrashReport(additionalInfo); MOZ_CRASH(CRASH_MESSAGE); @@ -3889,8 +3889,8 @@ - (void)keyDown:(NSEvent*)theEvent { TextInputHandler::IsSecureEventInputEnabled()) { # define CRASH_MESSAGE "A non-password editor has focus, but in secure input mode" - CrashReporter::AppendAppNotesToCrashReport(NS_LITERAL_CSTRING("\nBug 893973: ") + - NS_LITERAL_CSTRING(CRASH_MESSAGE)); + CrashReporter::AppendAppNotesToCrashReport("\nBug 893973: "_ns + + nsLiteralCString(CRASH_MESSAGE)); CrashReporter::AppendAppNotesToCrashReport(additionalInfo); MOZ_CRASH(CRASH_MESSAGE); diff --git a/widget/cocoa/nsDeviceContextSpecX.mm b/widget/cocoa/nsDeviceContextSpecX.mm index a3a4e1f9d2c8..ba65e9450044 100644 --- a/widget/cocoa/nsDeviceContextSpecX.mm +++ b/widget/cocoa/nsDeviceContextSpecX.mm @@ -215,19 +215,16 @@ // We don't actually currently support/use kOutputFormatPDF on mac, but // this is for completeness in case we add that (we probably need to in // order to support adding links into saved PDFs, for example). - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, NS_LITERAL_STRING("pdf_file"), - 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"pdf_file"_ns, 1); } else { PMDestinationType destination; OSStatus status = ::PMSessionGetDestinationType(mPrintSession, mPrintSettings, &destination); if (status == noErr && (destination == kPMDestinationFile || destination == kPMDestinationPreview || destination == kPMDestinationProcessPDF)) { - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, NS_LITERAL_STRING("pdf_file"), - 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"pdf_file"_ns, 1); } else { - Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, NS_LITERAL_STRING("unknown"), - 1); + Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, u"unknown"_ns, 1); } } diff --git a/widget/cocoa/nsFilePicker.mm b/widget/cocoa/nsFilePicker.mm index 197cf5984f85..5d2524d24931 100644 --- a/widget/cocoa/nsFilePicker.mm +++ b/widget/cocoa/nsFilePicker.mm @@ -513,7 +513,7 @@ - (void)menuChangedItem:(NSNotification*)aSender { return nil; } - if (filterWide.Equals(NS_LITERAL_STRING("*"))) { + if (filterWide.Equals(u"*"_ns)) { return nil; } @@ -616,7 +616,7 @@ - (void)menuChangedItem:(NSNotification*)aSender { nsFilePicker::AppendFilter(const nsAString& aTitle, const nsAString& aFilter) { // "..apps" has to be translated with native executable extensions. if (aFilter.EqualsLiteral("..apps")) { - mFilters.AppendElement(NS_LITERAL_STRING("*.app")); + mFilters.AppendElement(u"*.app"_ns); } else { mFilters.AppendElement(aFilter); } diff --git a/widget/cocoa/nsMacCursor.mm b/widget/cocoa/nsMacCursor.mm index a015dc38e225..ff656254c916 100644 --- a/widget/cocoa/nsMacCursor.mm +++ b/widget/cocoa/nsMacCursor.mm @@ -160,8 +160,8 @@ + (NSCursor*)cocoaCursorWithImageNamed:(NSString*)imageName hotSpot:(NSPoint)aPo nsresult rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(resDir)); if (NS_FAILED(rv)) goto INIT_FAILURE; - resDir->AppendNative(NS_LITERAL_CSTRING("res")); - resDir->AppendNative(NS_LITERAL_CSTRING("cursors")); + resDir->AppendNative("res"_ns); + resDir->AppendNative("cursors"_ns); rv = resDir->GetNativePath(resPath); if (NS_FAILED(rv)) goto INIT_FAILURE; diff --git a/widget/cocoa/nsMenuBarX.mm b/widget/cocoa/nsMenuBarX.mm index 369cc1121d17..06832bec04f9 100644 --- a/widget/cocoa/nsMenuBarX.mm +++ b/widget/cocoa/nsMenuBarX.mm @@ -491,7 +491,7 @@ - (void)menuDidClose:(NSMenu*)menu { nsIContent** outHiddenNode) { nsCOMPtr menuElement = inDoc->GetElementById(inID); if (menuElement) { - menuElement->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, NS_LITERAL_STRING("true"), false); + menuElement->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, u"true"_ns, false); if (outHiddenNode) { *outHiddenNode = menuElement.get(); NS_IF_ADDREF(*outHiddenNode); @@ -504,27 +504,27 @@ - (void)menuDidClose:(NSMenu*)menu { RefPtr domDoc = mContent->GetComposedDoc(); if (domDoc) { // remove the "About..." item and its separator - HideItem(domDoc, NS_LITERAL_STRING("aboutSeparator"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("aboutName"), getter_AddRefs(mAboutItemContent)); + HideItem(domDoc, u"aboutSeparator"_ns, nullptr); + HideItem(domDoc, u"aboutName"_ns, getter_AddRefs(mAboutItemContent)); if (!sAboutItemContent) sAboutItemContent = mAboutItemContent; // remove quit item and its separator - HideItem(domDoc, NS_LITERAL_STRING("menu_FileQuitSeparator"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_FileQuitItem"), getter_AddRefs(mQuitItemContent)); + HideItem(domDoc, u"menu_FileQuitSeparator"_ns, nullptr); + HideItem(domDoc, u"menu_FileQuitItem"_ns, getter_AddRefs(mQuitItemContent)); if (!sQuitItemContent) sQuitItemContent = mQuitItemContent; // remove prefs item and its separator, but save off the pref content node // so we can invoke its command later. - HideItem(domDoc, NS_LITERAL_STRING("menu_PrefsSeparator"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_preferences"), getter_AddRefs(mPrefItemContent)); + HideItem(domDoc, u"menu_PrefsSeparator"_ns, nullptr); + HideItem(domDoc, u"menu_preferences"_ns, getter_AddRefs(mPrefItemContent)); if (!sPrefItemContent) sPrefItemContent = mPrefItemContent; // hide items that we use for the Application menu - HideItem(domDoc, NS_LITERAL_STRING("menu_mac_services"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_mac_hide_app"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_mac_hide_others"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_mac_show_all"), nullptr); - HideItem(domDoc, NS_LITERAL_STRING("menu_mac_touch_bar"), nullptr); + HideItem(domDoc, u"menu_mac_services"_ns, nullptr); + HideItem(domDoc, u"menu_mac_hide_app"_ns, nullptr); + HideItem(domDoc, u"menu_mac_hide_others"_ns, nullptr); + HideItem(domDoc, u"menu_mac_show_all"_ns, nullptr); + HideItem(domDoc, u"menu_mac_touch_bar"_ns, nullptr); } } @@ -566,7 +566,7 @@ - (void)menuDidClose:(NSMenu*)menu { RefPtr keyElement = doc->GetElementById(key); if (keyElement) { // first grab the key equivalent character - nsAutoString keyChar(NS_LITERAL_STRING(" ")); + nsAutoString keyChar(u" "_ns); keyElement->GetAttr(kNameSpaceID_None, nsGkAtoms::key, keyChar); if (!keyChar.EqualsLiteral(" ")) { keyEquiv = [[NSString stringWithCharacters:reinterpret_cast(keyChar.get()) @@ -661,9 +661,8 @@ developers need only add each node with a label and a key equivalent (if they BOOL addAboutSeparator = FALSE; // Add the About menu item - itemBeingAdded = - CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("aboutName"), @selector(menuItemHit:), - eCommand_ID_About, nsMenuBarX::sNativeEventTarget); + itemBeingAdded = CreateNativeAppMenuItem(inMenu, u"aboutName"_ns, @selector(menuItemHit:), + eCommand_ID_About, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -676,9 +675,9 @@ developers need only add each node with a label and a key equivalent (if they if (addAboutSeparator) [sApplicationMenu addItem:[NSMenuItem separatorItem]]; // Add the Preferences menu item - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_preferences"), - @selector(menuItemHit:), eCommand_ID_Prefs, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_preferences"_ns, @selector(menuItemHit:), + eCommand_ID_Prefs, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -689,8 +688,7 @@ developers need only add each node with a label and a key equivalent (if they } // Add Services menu item - itemBeingAdded = - CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_mac_services"), nil, 0, nil); + itemBeingAdded = CreateNativeAppMenuItem(inMenu, u"menu_mac_services"_ns, nil, 0, nil); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; @@ -709,9 +707,9 @@ developers need only add each node with a label and a key equivalent (if they BOOL addHideShowSeparator = FALSE; // Add menu item to hide this application - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_mac_hide_app"), - @selector(menuItemHit:), eCommand_ID_HideApp, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_mac_hide_app"_ns, @selector(menuItemHit:), + eCommand_ID_HideApp, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -721,9 +719,9 @@ developers need only add each node with a label and a key equivalent (if they } // Add menu item to hide other applications - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_mac_hide_others"), - @selector(menuItemHit:), eCommand_ID_HideOthers, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_mac_hide_others"_ns, @selector(menuItemHit:), + eCommand_ID_HideOthers, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -733,9 +731,9 @@ developers need only add each node with a label and a key equivalent (if they } // Add menu item to show all applications - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_mac_show_all"), - @selector(menuItemHit:), eCommand_ID_ShowAll, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_mac_show_all"_ns, @selector(menuItemHit:), + eCommand_ID_ShowAll, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; @@ -750,9 +748,9 @@ developers need only add each node with a label and a key equivalent (if they BOOL addTouchBarSeparator = NO; // Add Touch Bar customization menu item. - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_mac_touch_bar"), - @selector(menuItemHit:), eCommand_ID_TouchBar, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_mac_touch_bar"_ns, @selector(menuItemHit:), + eCommand_ID_TouchBar, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; @@ -770,9 +768,9 @@ developers need only add each node with a label and a key equivalent (if they if (addTouchBarSeparator) [sApplicationMenu addItem:[NSMenuItem separatorItem]]; // Add quit menu item - itemBeingAdded = CreateNativeAppMenuItem(inMenu, NS_LITERAL_STRING("menu_FileQuitItem"), - @selector(menuItemHit:), eCommand_ID_Quit, - nsMenuBarX::sNativeEventTarget); + itemBeingAdded = + CreateNativeAppMenuItem(inMenu, u"menu_FileQuitItem"_ns, @selector(menuItemHit:), + eCommand_ID_Quit, nsMenuBarX::sNativeEventTarget); if (itemBeingAdded) { [sApplicationMenu addItem:itemBeingAdded]; [itemBeingAdded release]; diff --git a/widget/cocoa/nsMenuItemX.mm b/widget/cocoa/nsMenuItemX.mm index 0833a30ba476..92eb6a7ecf68 100644 --- a/widget/cocoa/nsMenuItemX.mm +++ b/widget/cocoa/nsMenuItemX.mm @@ -131,9 +131,8 @@ // update the content model. This will also handle unchecking our siblings // if we are a radiomenu - mContent->AsElement()->SetAttr( - kNameSpaceID_None, nsGkAtoms::checked, - mIsChecked ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false"), true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, + mIsChecked ? u"true"_ns : u"false"_ns, true); // update native menu item if (mIsChecked) @@ -171,7 +170,7 @@ // create DOM event ErrorResult rv; - RefPtr event = parentDoc->CreateEvent(NS_LITERAL_STRING("Events"), CallerType::System, rv); + RefPtr event = parentDoc->CreateEvent(u"Events"_ns, CallerType::System, rv); if (rv.Failed()) { NS_WARNING("Failed to create Event"); return rv.StealNSResult(); @@ -211,8 +210,7 @@ // if the current sibling is in the same group, clear it if (sibling->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, myGroupName, eCaseMatters)) { - sibling->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, - NS_LITERAL_STRING("false"), true); + sibling->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, u"false"_ns, true); } } } diff --git a/widget/cocoa/nsMenuUtilsX.mm b/widget/cocoa/nsMenuUtilsX.mm index 5bc169ee0c51..ea534d3f6e06 100644 --- a/widget/cocoa/nsMenuUtilsX.mm +++ b/widget/cocoa/nsMenuUtilsX.mm @@ -32,7 +32,7 @@ new dom::XULCommandEvent(doc, doc->GetPresContext(), nullptr); IgnoredErrorResult rv; - event->InitCommandEvent(NS_LITERAL_STRING("command"), true, true, + event->InitCommandEvent(u"command"_ns, true, true, nsGlobalWindowInner::Cast(doc->GetInnerWindow()), 0, false, false, false, false, nullptr, 0, rv); // FIXME: Should probably figure out how to init this with the actual diff --git a/widget/cocoa/nsMenuX.mm b/widget/cocoa/nsMenuX.mm index 1cb0f24a1f06..e0753899908f 100644 --- a/widget/cocoa/nsMenuX.mm +++ b/widget/cocoa/nsMenuX.mm @@ -315,8 +315,7 @@ - (void)setMenuGroupOwner:(nsMenuGroupOwnerX*)aMenuGroupOwner { nsEventStatus nsMenuX::MenuOpened() { // Open the node. if (mContent->IsElement()) { - mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, NS_LITERAL_STRING("true"), - true); + mContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::open, u"true"_ns, true); } // Fire a handler. If we're told to stop, don't build the menu at all @@ -590,7 +589,7 @@ - (void)setMenuGroupOwner:(nsMenuGroupOwnerX*)aMenuGroupOwner { if (aMenuContent && aMenuContent->IsElement()) { nsAutoString id; aMenuContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::id, id); - if (id.Equals(NS_LITERAL_STRING("helpMenu"))) retval = true; + if (id.Equals(u"helpMenu"_ns)) retval = true; } return retval; } @@ -716,8 +715,7 @@ - (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item { if (target && (target->MenuObjectType() == eMenuItemObjectType)) { nsMenuItemX* targetMenuItem = static_cast(target); bool handlerCalledPreventDefault; // but we don't actually care - targetMenuItem->DispatchDOMEvent(NS_LITERAL_STRING("DOMMenuItemActive"), - &handlerCalledPreventDefault); + targetMenuItem->DispatchDOMEvent(u"DOMMenuItemActive"_ns, &handlerCalledPreventDefault); } } diff --git a/widget/cocoa/nsNativeThemeCocoa.mm b/widget/cocoa/nsNativeThemeCocoa.mm index 2605a26f79b8..1f52f97df54d 100644 --- a/widget/cocoa/nsNativeThemeCocoa.mm +++ b/widget/cocoa/nsNativeThemeCocoa.mm @@ -2043,10 +2043,9 @@ static ThemeDrawState ToThemeDrawState(const nsNativeThemeCocoa::ControlParams& params.max = 100; } - params.reverse = - aFrame->GetContent()->IsElement() && - aFrame->GetContent()->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::dir, - NS_LITERAL_STRING("reverse"), eCaseMatters); + params.reverse = aFrame->GetContent()->IsElement() && + aFrame->GetContent()->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::dir, + u"reverse"_ns, eCaseMatters); params.insideActiveWindow = FrameIsInActiveWindow(aFrame); params.focused = aEventState.HasState(NS_EVENT_STATE_FOCUSRING); params.disabled = IsDisabled(aFrame, aEventState); @@ -2867,11 +2866,11 @@ static bool IsHiDPIContext(nsDeviceContext* aContext) { } SpinButtonParams params; if (content->IsElement()) { - if (content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::state, - NS_LITERAL_STRING("up"), eCaseMatters)) { + if (content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::state, u"up"_ns, + eCaseMatters)) { params.pressedButton = Some(SpinButton::eUp); } else if (content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::state, - NS_LITERAL_STRING("down"), eCaseMatters)) { + u"down"_ns, eCaseMatters)) { params.pressedButton = Some(SpinButton::eDown); } } diff --git a/widget/gtk/WakeLockListener.cpp b/widget/gtk/WakeLockListener.cpp index 5091f0b704f7..1d2328a5c63d 100644 --- a/widget/gtk/WakeLockListener.cpp +++ b/widget/gtk/WakeLockListener.cpp @@ -478,9 +478,8 @@ nsresult WakeLockListener::Callback(const nsAString& topic, return NS_ERROR_FAILURE; } - if (!topic.Equals(NS_LITERAL_STRING("screen")) && - !topic.Equals(NS_LITERAL_STRING("audio-playing")) && - !topic.Equals(NS_LITERAL_STRING("video-playing"))) + if (!topic.Equals(u"screen"_ns) && !topic.Equals(u"audio-playing"_ns) && + !topic.Equals(u"video-playing"_ns)) return NS_OK; WakeLockTopic* topicLock = mTopics.Get(topic); diff --git a/widget/gtk/nsClipboard.cpp b/widget/gtk/nsClipboard.cpp index 9eb3f3e0f9f6..568541981e4a 100644 --- a/widget/gtk/nsClipboard.cpp +++ b/widget/gtk/nsClipboard.cpp @@ -768,13 +768,11 @@ void GetHTMLCharset(const char* data, int32_t dataLength, nsCString& str) { htmlStr.EndReading(end); nsACString::const_iterator valueStart(start), valueEnd(start); - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("CONTENT=\"text/html;"), - start, end)) { + if (CaseInsensitiveFindInReadable("CONTENT=\"text/html;"_ns, start, end)) { start = end; htmlStr.EndReading(end); - if (CaseInsensitiveFindInReadable(NS_LITERAL_CSTRING("charset="), start, - end)) { + if (CaseInsensitiveFindInReadable("charset="_ns, start, end)) { valueStart = end; start = end; htmlStr.EndReading(end); diff --git a/widget/gtk/nsDragService.cpp b/widget/gtk/nsDragService.cpp index 197fd7752add..6eaf4776efca 100644 --- a/widget/gtk/nsDragService.cpp +++ b/widget/gtk/nsDragService.cpp @@ -1496,8 +1496,8 @@ void nsDragService::SourceDataGet(GtkWidget* aWidget, GdkDragContext* aContext, if (!infoService) return; nsAutoCString host; - if (NS_SUCCEEDED(infoService->GetPropertyAsACString( - NS_LITERAL_STRING("host"), host))) { + if (NS_SUCCEEDED( + infoService->GetPropertyAsACString(u"host"_ns, host))) { if (!host.Equals(hostname)) { MOZ_LOG(sDragLm, LogLevel::Debug, ("ignored drag because of different host.\n")); diff --git a/widget/gtk/nsGtkKeyUtils.cpp b/widget/gtk/nsGtkKeyUtils.cpp index 5f2930a37ab4..c1682eff2601 100644 --- a/widget/gtk/nsGtkKeyUtils.cpp +++ b/widget/gtk/nsGtkKeyUtils.cpp @@ -74,13 +74,13 @@ static const char* GetStatusName(nsEventStatus aStatus) { static const nsCString GetKeyLocationName(uint32_t aLocation) { switch (aLocation) { case eKeyLocationLeft: - return NS_LITERAL_CSTRING("KEY_LOCATION_LEFT"); + return "KEY_LOCATION_LEFT"_ns; case eKeyLocationRight: - return NS_LITERAL_CSTRING("KEY_LOCATION_RIGHT"); + return "KEY_LOCATION_RIGHT"_ns; case eKeyLocationStandard: - return NS_LITERAL_CSTRING("KEY_LOCATION_STANDARD"); + return "KEY_LOCATION_STANDARD"_ns; case eKeyLocationNumpad: - return NS_LITERAL_CSTRING("KEY_LOCATION_NUMPAD"); + return "KEY_LOCATION_NUMPAD"_ns; default: return nsPrintfCString("Unknown (0x%04X)", aLocation); } @@ -89,87 +89,87 @@ static const nsCString GetKeyLocationName(uint32_t aLocation) { static const nsCString GetCharacterCodeName(char16_t aChar) { switch (aChar) { case 0x0000: - return NS_LITERAL_CSTRING("NULL (0x0000)"); + return "NULL (0x0000)"_ns; case 0x0008: - return NS_LITERAL_CSTRING("BACKSPACE (0x0008)"); + return "BACKSPACE (0x0008)"_ns; case 0x0009: - return NS_LITERAL_CSTRING("CHARACTER TABULATION (0x0009)"); + return "CHARACTER TABULATION (0x0009)"_ns; case 0x000A: - return NS_LITERAL_CSTRING("LINE FEED (0x000A)"); + return "LINE FEED (0x000A)"_ns; case 0x000B: - return NS_LITERAL_CSTRING("LINE TABULATION (0x000B)"); + return "LINE TABULATION (0x000B)"_ns; case 0x000C: - return NS_LITERAL_CSTRING("FORM FEED (0x000C)"); + return "FORM FEED (0x000C)"_ns; case 0x000D: - return NS_LITERAL_CSTRING("CARRIAGE RETURN (0x000D)"); + return "CARRIAGE RETURN (0x000D)"_ns; case 0x0018: - return NS_LITERAL_CSTRING("CANCEL (0x0018)"); + return "CANCEL (0x0018)"_ns; case 0x001B: - return NS_LITERAL_CSTRING("ESCAPE (0x001B)"); + return "ESCAPE (0x001B)"_ns; case 0x0020: - return NS_LITERAL_CSTRING("SPACE (0x0020)"); + return "SPACE (0x0020)"_ns; case 0x007F: - return NS_LITERAL_CSTRING("DELETE (0x007F)"); + return "DELETE (0x007F)"_ns; case 0x00A0: - return NS_LITERAL_CSTRING("NO-BREAK SPACE (0x00A0)"); + return "NO-BREAK SPACE (0x00A0)"_ns; case 0x00AD: - return NS_LITERAL_CSTRING("SOFT HYPHEN (0x00AD)"); + return "SOFT HYPHEN (0x00AD)"_ns; case 0x2000: - return NS_LITERAL_CSTRING("EN QUAD (0x2000)"); + return "EN QUAD (0x2000)"_ns; case 0x2001: - return NS_LITERAL_CSTRING("EM QUAD (0x2001)"); + return "EM QUAD (0x2001)"_ns; case 0x2002: - return NS_LITERAL_CSTRING("EN SPACE (0x2002)"); + return "EN SPACE (0x2002)"_ns; case 0x2003: - return NS_LITERAL_CSTRING("EM SPACE (0x2003)"); + return "EM SPACE (0x2003)"_ns; case 0x2004: - return NS_LITERAL_CSTRING("THREE-PER-EM SPACE (0x2004)"); + return "THREE-PER-EM SPACE (0x2004)"_ns; case 0x2005: - return NS_LITERAL_CSTRING("FOUR-PER-EM SPACE (0x2005)"); + return "FOUR-PER-EM SPACE (0x2005)"_ns; case 0x2006: - return NS_LITERAL_CSTRING("SIX-PER-EM SPACE (0x2006)"); + return "SIX-PER-EM SPACE (0x2006)"_ns; case 0x2007: - return NS_LITERAL_CSTRING("FIGURE SPACE (0x2007)"); + return "FIGURE SPACE (0x2007)"_ns; case 0x2008: - return NS_LITERAL_CSTRING("PUNCTUATION SPACE (0x2008)"); + return "PUNCTUATION SPACE (0x2008)"_ns; case 0x2009: - return NS_LITERAL_CSTRING("THIN SPACE (0x2009)"); + return "THIN SPACE (0x2009)"_ns; case 0x200A: - return NS_LITERAL_CSTRING("HAIR SPACE (0x200A)"); + return "HAIR SPACE (0x200A)"_ns; case 0x200B: - return NS_LITERAL_CSTRING("ZERO WIDTH SPACE (0x200B)"); + return "ZERO WIDTH SPACE (0x200B)"_ns; case 0x200C: - return NS_LITERAL_CSTRING("ZERO WIDTH NON-JOINER (0x200C)"); + return "ZERO WIDTH NON-JOINER (0x200C)"_ns; case 0x200D: - return NS_LITERAL_CSTRING("ZERO WIDTH JOINER (0x200D)"); + return "ZERO WIDTH JOINER (0x200D)"_ns; case 0x200E: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT MARK (0x200E)"); + return "LEFT-TO-RIGHT MARK (0x200E)"_ns; case 0x200F: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT MARK (0x200F)"); + return "RIGHT-TO-LEFT MARK (0x200F)"_ns; case 0x2029: - return NS_LITERAL_CSTRING("PARAGRAPH SEPARATOR (0x2029)"); + return "PARAGRAPH SEPARATOR (0x2029)"_ns; case 0x202A: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT EMBEDDING (0x202A)"); + return "LEFT-TO-RIGHT EMBEDDING (0x202A)"_ns; case 0x202B: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT EMBEDDING (0x202B)"); + return "RIGHT-TO-LEFT EMBEDDING (0x202B)"_ns; case 0x202D: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT OVERRIDE (0x202D)"); + return "LEFT-TO-RIGHT OVERRIDE (0x202D)"_ns; case 0x202E: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT OVERRIDE (0x202E)"); + return "RIGHT-TO-LEFT OVERRIDE (0x202E)"_ns; case 0x202F: - return NS_LITERAL_CSTRING("NARROW NO-BREAK SPACE (0x202F)"); + return "NARROW NO-BREAK SPACE (0x202F)"_ns; case 0x205F: - return NS_LITERAL_CSTRING("MEDIUM MATHEMATICAL SPACE (0x205F)"); + return "MEDIUM MATHEMATICAL SPACE (0x205F)"_ns; case 0x2060: - return NS_LITERAL_CSTRING("WORD JOINER (0x2060)"); + return "WORD JOINER (0x2060)"_ns; case 0x2066: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT ISOLATE (0x2066)"); + return "LEFT-TO-RIGHT ISOLATE (0x2066)"_ns; case 0x2067: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT ISOLATE (0x2067)"); + return "RIGHT-TO-LEFT ISOLATE (0x2067)"_ns; case 0x3000: - return NS_LITERAL_CSTRING("IDEOGRAPHIC SPACE (0x3000)"); + return "IDEOGRAPHIC SPACE (0x3000)"_ns; case 0xFEFF: - return NS_LITERAL_CSTRING("ZERO WIDTH NO-BREAK SPACE (0xFEFF)"); + return "ZERO WIDTH NO-BREAK SPACE (0xFEFF)"_ns; default: { if (aChar < ' ' || (aChar >= 0x80 && aChar < 0xA0)) { return nsPrintfCString("control (0x%04X)", aChar); @@ -190,7 +190,7 @@ static const nsCString GetCharacterCodeName(char16_t aChar) { static const nsCString GetCharacterCodeNames(const char16_t* aChars, uint32_t aLength) { if (!aLength) { - return NS_LITERAL_CSTRING("\"\""); + return "\"\""_ns; } nsCString result; for (uint32_t i = 0; i < aLength; ++i) { diff --git a/widget/gtk/nsLookAndFeel.cpp b/widget/gtk/nsLookAndFeel.cpp index 302674ebb05b..8aca6e4e8ed2 100644 --- a/widget/gtk/nsLookAndFeel.cpp +++ b/widget/gtk/nsLookAndFeel.cpp @@ -1033,7 +1033,7 @@ void nsLookAndFeel::EnsureInit() { RelativeLuminanceUtils::Compute(GDK_RGBA_TO_NS_RGBA(fg))); mHighContrast = StaticPrefs::widget_content_gtk_high_contrast_enabled() && - GetGtkTheme().Find(NS_LITERAL_CSTRING("HighContrast")) >= 0; + GetGtkTheme().Find("HighContrast"_ns) >= 0; gboolean enableAnimations = false; g_object_get(settings, "gtk-enable-animations", &enableAnimations, nullptr); diff --git a/widget/gtk/nsPSPrinters.cpp b/widget/gtk/nsPSPrinters.cpp index d98bd2ccb105..16e48f10f70f 100644 --- a/widget/gtk/nsPSPrinters.cpp +++ b/widget/gtk/nsPSPrinters.cpp @@ -75,7 +75,7 @@ void nsPSPrinterList::GetPrinterList(nsTArray& aList) { // MOZILLA_POSTSCRIPT_PRINTER_LIST or a preference setting // print.printer_list, which contains a space-separated list of printer // names. - aList.AppendElement(NS_LITERAL_CSTRING(NS_POSTSCRIPT_DRIVER_NAME "default")); + aList.AppendElement(nsLiteralCString(NS_POSTSCRIPT_DRIVER_NAME "default")); nsAutoCString list(PR_GetEnv("MOZILLA_POSTSCRIPT_PRINTER_LIST")); if (list.IsEmpty()) { @@ -100,10 +100,10 @@ void nsPSPrinterList::GetPrinterList(nsTArray& aList) { /* Identify the printer type */ nsPSPrinterList::PrinterType nsPSPrinterList::GetPrinterType( const nsACString& aName) { - if (StringBeginsWith(aName, NS_LITERAL_CSTRING(NS_POSTSCRIPT_DRIVER_NAME))) { + if (StringBeginsWith(aName, nsLiteralCString(NS_POSTSCRIPT_DRIVER_NAME))) { return kTypePS; } - if (StringBeginsWith(aName, NS_LITERAL_CSTRING(NS_CUPS_PRINTER))) { + if (StringBeginsWith(aName, nsLiteralCString(NS_CUPS_PRINTER))) { return kTypeCUPS; } return kTypeUnknown; diff --git a/widget/gtk/nsPrintSettingsGTK.cpp b/widget/gtk/nsPrintSettingsGTK.cpp index 2490ce729e2b..ccbab80e0a12 100644 --- a/widget/gtk/nsPrintSettingsGTK.cpp +++ b/widget/gtk/nsPrintSettingsGTK.cpp @@ -424,7 +424,7 @@ NS_IMETHODIMP nsPrintSettingsGTK::SetPrinterName(const nsAString& aPrinter) { NS_ConvertUTF16toUTF8 gtkPrinter(aPrinter); - if (StringBeginsWith(gtkPrinter, NS_LITERAL_CSTRING("CUPS/"))) { + if (StringBeginsWith(gtkPrinter, "CUPS/"_ns)) { // Strip off "CUPS/"; GTK might recognize the rest gtkPrinter.Cut(0, strlen("CUPS/")); } diff --git a/widget/gtk/nsWindow.cpp b/widget/gtk/nsWindow.cpp index 18cb9223fd7f..7b2badcb5c20 100644 --- a/widget/gtk/nsWindow.cpp +++ b/widget/gtk/nsWindow.cpp @@ -1888,12 +1888,12 @@ static bool DesktopUsesDynamicWorkspaces(GdkWindow* gdk_window) { do_GetService(NS_GSETTINGSSERVICE_CONTRACTID); if (gsettings) { nsCOMPtr mutterSettings; - gsettings->GetCollectionForSchema(NS_LITERAL_CSTRING(kDesktopMutterSchema), + gsettings->GetCollectionForSchema(nsLiteralCString(kDesktopMutterSchema), getter_AddRefs(mutterSettings)); if (mutterSettings) { bool usesDynamicWorkspaces; if (NS_SUCCEEDED(mutterSettings->GetBoolean( - NS_LITERAL_CSTRING(kDesktopDynamicWorkspacesKey), + nsLiteralCString(kDesktopDynamicWorkspacesKey), &usesDynamicWorkspaces))) { return usesDynamicWorkspaces; } @@ -5881,7 +5881,7 @@ void nsWindow::SetUrgencyHint(GtkWidget* top_window, bool state) { gdk_window_set_urgency_hint(gtk_widget_get_window(top_window), state); } -void nsWindow::SetDefaultIcon(void) { SetIcon(NS_LITERAL_STRING("default")); } +void nsWindow::SetDefaultIcon(void) { SetIcon(u"default"_ns); } gint nsWindow::ConvertBorderStyles(nsBorderStyle aStyle) { gint w = 0; diff --git a/widget/nsBaseFilePicker.cpp b/widget/nsBaseFilePicker.cpp index bfd9f7714bd1..8cc2369c95a3 100644 --- a/widget/nsBaseFilePicker.cpp +++ b/widget/nsBaseFilePicker.cpp @@ -233,7 +233,7 @@ nsBaseFilePicker::AppendFilters(int32_t aFilterMask) { titleBundle->GetStringFromName("appsTitle", title); // Pass the magic string "..apps" to the platform filepicker, which it // should recognize and do the correct platform behavior for. - AppendFilter(title, NS_LITERAL_STRING("..apps")); + AppendFilter(title, u"..apps"_ns); } return NS_OK; } diff --git a/widget/nsBaseWidget.cpp b/widget/nsBaseWidget.cpp index 9455e00dae7e..98ab3731c439 100644 --- a/widget/nsBaseWidget.cpp +++ b/widget/nsBaseWidget.cpp @@ -1535,8 +1535,8 @@ bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) { */ static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName, const nsAString& aIconSuffix) { - aFile->Append(NS_LITERAL_STRING("icons")); - aFile->Append(NS_LITERAL_STRING("default")); + aFile->Append(u"icons"_ns); + aFile->Append(u"default"_ns); aFile->Append(aIconName + aIconSuffix); bool readable; @@ -3032,7 +3032,7 @@ void IMENotification::TextChangeDataBase::Test() { nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) { NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event."); - nsAutoString eventName(NS_LITERAL_STRING("UNKNOWN")); + nsAutoString eventName(u"UNKNOWN"_ns); # define _ASSIGN_eventName(_value, _name) \ case _value: \ diff --git a/widget/nsHTMLFormatConverter.cpp b/widget/nsHTMLFormatConverter.cpp index 691dfa54b08d..59ec15c7c1bf 100644 --- a/widget/nsHTMLFormatConverter.cpp +++ b/widget/nsHTMLFormatConverter.cpp @@ -32,7 +32,7 @@ NS_IMPL_ISUPPORTS(nsHTMLFormatConverter, nsIFormatConverter) // NS_IMETHODIMP nsHTMLFormatConverter::GetInputDataFlavors(nsTArray& aFlavors) { - aFlavors.AppendElement(NS_LITERAL_CSTRING(kHTMLMime)); + aFlavors.AppendElement(nsLiteralCString(kHTMLMime)); return NS_OK; } @@ -45,8 +45,8 @@ nsHTMLFormatConverter::GetInputDataFlavors(nsTArray& aFlavors) { // NS_IMETHODIMP nsHTMLFormatConverter::GetOutputDataFlavors(nsTArray& aFlavors) { - aFlavors.AppendElement(NS_LITERAL_CSTRING(kHTMLMime)); - aFlavors.AppendElement(NS_LITERAL_CSTRING(kUnicodeMime)); + aFlavors.AppendElement(nsLiteralCString(kHTMLMime)); + aFlavors.AppendElement(nsLiteralCString(kUnicodeMime)); return NS_OK; } diff --git a/widget/nsNativeTheme.cpp b/widget/nsNativeTheme.cpp index ad993d566074..d4f3aa401a3d 100644 --- a/widget/nsNativeTheme.cpp +++ b/widget/nsNativeTheme.cpp @@ -87,8 +87,8 @@ bool nsNativeTheme::CheckBooleanAttr(nsIFrame* aFrame, nsAtom* aAtom) { // For XML/XUL elements, an attribute must be equal to the literal // string "true" to be counted as true. An empty string should _not_ // be counted as true. - return content->AsElement()->AttrValueIs( - kNameSpaceID_None, aAtom, NS_LITERAL_STRING("true"), eCaseMatters); + return content->AsElement()->AttrValueIs(kNameSpaceID_None, aAtom, u"true"_ns, + eCaseMatters); } /* static */ @@ -154,8 +154,7 @@ bool nsNativeTheme::IsButtonTypeMenu(nsIFrame* aFrame) { nsIContent* content = aFrame->GetContent(); return content->IsXULElement(nsGkAtoms::button) && content->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, - NS_LITERAL_STRING("menu"), - eCaseMatters); + u"menu"_ns, eCaseMatters); } bool nsNativeTheme::IsPressedButton(nsIFrame* aFrame) { @@ -294,8 +293,7 @@ bool nsNativeTheme::IsDisabled(nsIFrame* aFrame, EventStates aEventStates) { // string "true" to be counted as true. An empty string should _not_ // be counted as true. return content->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::disabled, NS_LITERAL_STRING("true"), - eCaseMatters); + kNameSpaceID_None, nsGkAtoms::disabled, u"true"_ns, eCaseMatters); } /* static */ @@ -378,9 +376,9 @@ bool nsNativeTheme::IsLastTreeHeaderCell(nsIFrame* aFrame) { } // If the column picker is visible, this can't be the last column. - if (parent && !parent->AsElement()->AttrValueIs( - kNameSpaceID_None, nsGkAtoms::hidecolumnpicker, - NS_LITERAL_STRING("true"), eCaseMatters)) + if (parent && !parent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::hidecolumnpicker, + u"true"_ns, eCaseMatters)) return false; while ((aFrame = aFrame->GetNextSibling())) { diff --git a/widget/nsPrintSettingsService.cpp b/widget/nsPrintSettingsService.cpp index 7ad764b261f8..3715fffaddd5 100644 --- a/widget/nsPrintSettingsService.cpp +++ b/widget/nsPrintSettingsService.cpp @@ -538,7 +538,7 @@ nsresult nsPrintSettingsService::ReadPrefs(nsIPrintSettings* aPS, if (aFlags & nsIPrintSettings::kInitSaveToFileName) { if (GETSTRPREF(kPrintToFileName, str)) { - if (StringEndsWith(str, NS_LITERAL_STRING(".ps"))) { + if (StringEndsWith(str, u".ps"_ns)) { // We only support PDF since bug 1425188 landed. Users may still have // prefs with .ps filenames if they last saved a file as Postscript // though, so we fix that up here. (The pref values will be diff --git a/widget/windows/GfxInfo.cpp b/widget/windows/GfxInfo.cpp index 5e5bda93cd52..45bb03e2b89d 100644 --- a/widget/windows/GfxInfo.cpp +++ b/widget/windows/GfxInfo.cpp @@ -468,11 +468,11 @@ nsresult GfxInfo::Init() { } } - mDeviceKeyDebug = NS_LITERAL_STRING("PrimarySearch"); + mDeviceKeyDebug = u"PrimarySearch"_ns; while (EnumDisplayDevicesW(nullptr, deviceIndex, &displayDevice, 0)) { if (displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) { - mDeviceKeyDebug = NS_LITERAL_STRING("NullSearch"); + mDeviceKeyDebug = u"NullSearch"_ns; break; } deviceIndex++; @@ -778,12 +778,12 @@ nsresult GfxInfo::Init() { nsAutoString eligibleDLLs; if (NS_SUCCEEDED(GetAdapterDriver(eligibleDLLs))) { if (FindInReadable(dllFileName, eligibleDLLs)) { - dllFileName += NS_LITERAL_STRING(".dll"); + dllFileName += u".dll"_ns; gfxWindowsPlatform::GetDLLVersion(dllFileName.get(), dllVersion); ParseDriverVersion(dllVersion, &dllNumericVersion); } if (FindInReadable(dllFileName2, eligibleDLLs)) { - dllFileName2 += NS_LITERAL_STRING(".dll"); + dllFileName2 += u".dll"_ns; gfxWindowsPlatform::GetDLLVersion(dllFileName2.get(), dllVersion2); ParseDriverVersion(dllVersion2, &dllNumericVersion2); } @@ -814,8 +814,7 @@ nsresult GfxInfo::Init() { } ParseDriverVersion(mDriverVersion[mActiveGPUIndex], &driverNumericVersion); - ParseDriverVersion(NS_LITERAL_STRING("9.17.10.0"), - &knownSafeMismatchVersion); + ParseDriverVersion(u"9.17.10.0"_ns, &knownSafeMismatchVersion); // If there's a driver version mismatch, consider this harmful only when // the driver version is less than knownSafeMismatchVersion. See the @@ -1089,8 +1088,7 @@ static void CheckForCiscoVPN() { 0, KEY_QUERY_VALUE, &key); if (result == ERROR_SUCCESS) { RegCloseKey(key); - CrashReporter::AppendAppNotesToCrashReport( - NS_LITERAL_CSTRING("Cisco VPN\n")); + CrashReporter::AppendAppNotesToCrashReport("Cisco VPN\n"_ns); } } @@ -1098,8 +1096,7 @@ void GfxInfo::AddCrashReportAnnotations() { CheckForCiscoVPN(); if (mHasDriverVersionMismatch) { - CrashReporter::AppendAppNotesToCrashReport( - NS_LITERAL_CSTRING("DriverVersionMismatch\n")); + CrashReporter::AppendAppNotesToCrashReport("DriverVersionMismatch\n"_ns); } nsString deviceID, vendorID, driverVersion, subsysID; diff --git a/widget/windows/JumpListBuilder.cpp b/widget/windows/JumpListBuilder.cpp index 2e0462632476..fa14dd7cb5f8 100644 --- a/widget/windows/JumpListBuilder.cpp +++ b/widget/windows/JumpListBuilder.cpp @@ -117,8 +117,7 @@ JumpListBuilder::JumpListBuilder() } // Make a lazy thread for any IO - mIOThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, - NS_LITERAL_CSTRING("Jump List"), + mIOThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, "Jump List"_ns, LazyIdleThread::ManualShutdown); Preferences::AddStrongObserver(this, kPrefTaskbarEnabled); diff --git a/widget/windows/KeyboardLayout.cpp b/widget/windows/KeyboardLayout.cpp index 798f73f54d2b..12121fe0a6af 100644 --- a/widget/windows/KeyboardLayout.cpp +++ b/widget/windows/KeyboardLayout.cpp @@ -329,87 +329,87 @@ static const char* GetBoolName(bool aBool) { return aBool ? "true" : "false"; } static const nsCString GetCharacterCodeName(WPARAM aCharCode) { switch (aCharCode) { case 0x0000: - return NS_LITERAL_CSTRING("NULL (0x0000)"); + return "NULL (0x0000)"_ns; case 0x0008: - return NS_LITERAL_CSTRING("BACKSPACE (0x0008)"); + return "BACKSPACE (0x0008)"_ns; case 0x0009: - return NS_LITERAL_CSTRING("CHARACTER TABULATION (0x0009)"); + return "CHARACTER TABULATION (0x0009)"_ns; case 0x000A: - return NS_LITERAL_CSTRING("LINE FEED (0x000A)"); + return "LINE FEED (0x000A)"_ns; case 0x000B: - return NS_LITERAL_CSTRING("LINE TABULATION (0x000B)"); + return "LINE TABULATION (0x000B)"_ns; case 0x000C: - return NS_LITERAL_CSTRING("FORM FEED (0x000C)"); + return "FORM FEED (0x000C)"_ns; case 0x000D: - return NS_LITERAL_CSTRING("CARRIAGE RETURN (0x000D)"); + return "CARRIAGE RETURN (0x000D)"_ns; case 0x0018: - return NS_LITERAL_CSTRING("CANCEL (0x0018)"); + return "CANCEL (0x0018)"_ns; case 0x001B: - return NS_LITERAL_CSTRING("ESCAPE (0x001B)"); + return "ESCAPE (0x001B)"_ns; case 0x0020: - return NS_LITERAL_CSTRING("SPACE (0x0020)"); + return "SPACE (0x0020)"_ns; case 0x007F: - return NS_LITERAL_CSTRING("DELETE (0x007F)"); + return "DELETE (0x007F)"_ns; case 0x00A0: - return NS_LITERAL_CSTRING("NO-BREAK SPACE (0x00A0)"); + return "NO-BREAK SPACE (0x00A0)"_ns; case 0x00AD: - return NS_LITERAL_CSTRING("SOFT HYPHEN (0x00AD)"); + return "SOFT HYPHEN (0x00AD)"_ns; case 0x2000: - return NS_LITERAL_CSTRING("EN QUAD (0x2000)"); + return "EN QUAD (0x2000)"_ns; case 0x2001: - return NS_LITERAL_CSTRING("EM QUAD (0x2001)"); + return "EM QUAD (0x2001)"_ns; case 0x2002: - return NS_LITERAL_CSTRING("EN SPACE (0x2002)"); + return "EN SPACE (0x2002)"_ns; case 0x2003: - return NS_LITERAL_CSTRING("EM SPACE (0x2003)"); + return "EM SPACE (0x2003)"_ns; case 0x2004: - return NS_LITERAL_CSTRING("THREE-PER-EM SPACE (0x2004)"); + return "THREE-PER-EM SPACE (0x2004)"_ns; case 0x2005: - return NS_LITERAL_CSTRING("FOUR-PER-EM SPACE (0x2005)"); + return "FOUR-PER-EM SPACE (0x2005)"_ns; case 0x2006: - return NS_LITERAL_CSTRING("SIX-PER-EM SPACE (0x2006)"); + return "SIX-PER-EM SPACE (0x2006)"_ns; case 0x2007: - return NS_LITERAL_CSTRING("FIGURE SPACE (0x2007)"); + return "FIGURE SPACE (0x2007)"_ns; case 0x2008: - return NS_LITERAL_CSTRING("PUNCTUATION SPACE (0x2008)"); + return "PUNCTUATION SPACE (0x2008)"_ns; case 0x2009: - return NS_LITERAL_CSTRING("THIN SPACE (0x2009)"); + return "THIN SPACE (0x2009)"_ns; case 0x200A: - return NS_LITERAL_CSTRING("HAIR SPACE (0x200A)"); + return "HAIR SPACE (0x200A)"_ns; case 0x200B: - return NS_LITERAL_CSTRING("ZERO WIDTH SPACE (0x200B)"); + return "ZERO WIDTH SPACE (0x200B)"_ns; case 0x200C: - return NS_LITERAL_CSTRING("ZERO WIDTH NON-JOINER (0x200C)"); + return "ZERO WIDTH NON-JOINER (0x200C)"_ns; case 0x200D: - return NS_LITERAL_CSTRING("ZERO WIDTH JOINER (0x200D)"); + return "ZERO WIDTH JOINER (0x200D)"_ns; case 0x200E: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT MARK (0x200E)"); + return "LEFT-TO-RIGHT MARK (0x200E)"_ns; case 0x200F: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT MARK (0x200F)"); + return "RIGHT-TO-LEFT MARK (0x200F)"_ns; case 0x2029: - return NS_LITERAL_CSTRING("PARAGRAPH SEPARATOR (0x2029)"); + return "PARAGRAPH SEPARATOR (0x2029)"_ns; case 0x202A: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT EMBEDDING (0x202A)"); + return "LEFT-TO-RIGHT EMBEDDING (0x202A)"_ns; case 0x202B: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT EMBEDDING (0x202B)"); + return "RIGHT-TO-LEFT EMBEDDING (0x202B)"_ns; case 0x202D: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT OVERRIDE (0x202D)"); + return "LEFT-TO-RIGHT OVERRIDE (0x202D)"_ns; case 0x202E: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT OVERRIDE (0x202E)"); + return "RIGHT-TO-LEFT OVERRIDE (0x202E)"_ns; case 0x202F: - return NS_LITERAL_CSTRING("NARROW NO-BREAK SPACE (0x202F)"); + return "NARROW NO-BREAK SPACE (0x202F)"_ns; case 0x205F: - return NS_LITERAL_CSTRING("MEDIUM MATHEMATICAL SPACE (0x205F)"); + return "MEDIUM MATHEMATICAL SPACE (0x205F)"_ns; case 0x2060: - return NS_LITERAL_CSTRING("WORD JOINER (0x2060)"); + return "WORD JOINER (0x2060)"_ns; case 0x2066: - return NS_LITERAL_CSTRING("LEFT-TO-RIGHT ISOLATE (0x2066)"); + return "LEFT-TO-RIGHT ISOLATE (0x2066)"_ns; case 0x2067: - return NS_LITERAL_CSTRING("RIGHT-TO-LEFT ISOLATE (0x2067)"); + return "RIGHT-TO-LEFT ISOLATE (0x2067)"_ns; case 0x3000: - return NS_LITERAL_CSTRING("IDEOGRAPHIC SPACE (0x3000)"); + return "IDEOGRAPHIC SPACE (0x3000)"_ns; case 0xFEFF: - return NS_LITERAL_CSTRING("ZERO WIDTH NO-BREAK SPACE (0xFEFF)"); + return "ZERO WIDTH NO-BREAK SPACE (0xFEFF)"_ns; default: { if (aCharCode < ' ' || (aCharCode >= 0x80 && aCharCode < 0xA0)) { return nsPrintfCString("control (0x%04X)", aCharCode); @@ -436,13 +436,13 @@ static const nsCString GetCharacterCodeName(WPARAM aCharCode) { static const nsCString GetKeyLocationName(uint32_t aLocation) { switch (aLocation) { case eKeyLocationLeft: - return NS_LITERAL_CSTRING("KEY_LOCATION_LEFT"); + return "KEY_LOCATION_LEFT"_ns; case eKeyLocationRight: - return NS_LITERAL_CSTRING("KEY_LOCATION_RIGHT"); + return "KEY_LOCATION_RIGHT"_ns; case eKeyLocationStandard: - return NS_LITERAL_CSTRING("KEY_LOCATION_STANDARD"); + return "KEY_LOCATION_STANDARD"_ns; case eKeyLocationNumpad: - return NS_LITERAL_CSTRING("KEY_LOCATION_NUMPAD"); + return "KEY_LOCATION_NUMPAD"_ns; default: return nsPrintfCString("Unknown (0x%04X)", aLocation); } @@ -524,33 +524,33 @@ class MOZ_STACK_CLASS GetShiftStateName final : public nsAutoCString { static const nsCString GetMessageName(UINT aMessage) { switch (aMessage) { case WM_NULL: - return NS_LITERAL_CSTRING("WM_NULL"); + return "WM_NULL"_ns; case WM_KEYDOWN: - return NS_LITERAL_CSTRING("WM_KEYDOWN"); + return "WM_KEYDOWN"_ns; case WM_KEYUP: - return NS_LITERAL_CSTRING("WM_KEYUP"); + return "WM_KEYUP"_ns; case WM_SYSKEYDOWN: - return NS_LITERAL_CSTRING("WM_SYSKEYDOWN"); + return "WM_SYSKEYDOWN"_ns; case WM_SYSKEYUP: - return NS_LITERAL_CSTRING("WM_SYSKEYUP"); + return "WM_SYSKEYUP"_ns; case WM_CHAR: - return NS_LITERAL_CSTRING("WM_CHAR"); + return "WM_CHAR"_ns; case WM_UNICHAR: - return NS_LITERAL_CSTRING("WM_UNICHAR"); + return "WM_UNICHAR"_ns; case WM_SYSCHAR: - return NS_LITERAL_CSTRING("WM_SYSCHAR"); + return "WM_SYSCHAR"_ns; case WM_DEADCHAR: - return NS_LITERAL_CSTRING("WM_DEADCHAR"); + return "WM_DEADCHAR"_ns; case WM_SYSDEADCHAR: - return NS_LITERAL_CSTRING("WM_SYSDEADCHAR"); + return "WM_SYSDEADCHAR"_ns; case MOZ_WM_KEYDOWN: - return NS_LITERAL_CSTRING("MOZ_WM_KEYDOWN"); + return "MOZ_WM_KEYDOWN"_ns; case MOZ_WM_KEYUP: - return NS_LITERAL_CSTRING("MOZ_WM_KEYUP"); + return "MOZ_WM_KEYUP"_ns; case WM_APPCOMMAND: - return NS_LITERAL_CSTRING("WM_APPCOMMAND"); + return "WM_APPCOMMAND"_ns; case WM_QUIT: - return NS_LITERAL_CSTRING("WM_QUIT"); + return "WM_QUIT"_ns; default: return nsPrintfCString("Unknown Message (0x%04X)", aMessage); } @@ -566,109 +566,109 @@ static const nsCString GetVirtualKeyCodeName(WPARAM aVK) { static const nsCString GetAppCommandName(WPARAM aCommand) { switch (aCommand) { case APPCOMMAND_BASS_BOOST: - return NS_LITERAL_CSTRING("APPCOMMAND_BASS_BOOST"); + return "APPCOMMAND_BASS_BOOST"_ns; case APPCOMMAND_BASS_DOWN: - return NS_LITERAL_CSTRING("APPCOMMAND_BASS_DOWN"); + return "APPCOMMAND_BASS_DOWN"_ns; case APPCOMMAND_BASS_UP: - return NS_LITERAL_CSTRING("APPCOMMAND_BASS_UP"); + return "APPCOMMAND_BASS_UP"_ns; case APPCOMMAND_BROWSER_BACKWARD: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_BACKWARD"); + return "APPCOMMAND_BROWSER_BACKWARD"_ns; case APPCOMMAND_BROWSER_FAVORITES: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_FAVORITES"); + return "APPCOMMAND_BROWSER_FAVORITES"_ns; case APPCOMMAND_BROWSER_FORWARD: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_FORWARD"); + return "APPCOMMAND_BROWSER_FORWARD"_ns; case APPCOMMAND_BROWSER_HOME: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_HOME"); + return "APPCOMMAND_BROWSER_HOME"_ns; case APPCOMMAND_BROWSER_REFRESH: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_REFRESH"); + return "APPCOMMAND_BROWSER_REFRESH"_ns; case APPCOMMAND_BROWSER_SEARCH: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_SEARCH"); + return "APPCOMMAND_BROWSER_SEARCH"_ns; case APPCOMMAND_BROWSER_STOP: - return NS_LITERAL_CSTRING("APPCOMMAND_BROWSER_STOP"); + return "APPCOMMAND_BROWSER_STOP"_ns; case APPCOMMAND_CLOSE: - return NS_LITERAL_CSTRING("APPCOMMAND_CLOSE"); + return "APPCOMMAND_CLOSE"_ns; case APPCOMMAND_COPY: - return NS_LITERAL_CSTRING("APPCOMMAND_COPY"); + return "APPCOMMAND_COPY"_ns; case APPCOMMAND_CORRECTION_LIST: - return NS_LITERAL_CSTRING("APPCOMMAND_CORRECTION_LIST"); + return "APPCOMMAND_CORRECTION_LIST"_ns; case APPCOMMAND_CUT: - return NS_LITERAL_CSTRING("APPCOMMAND_CUT"); + return "APPCOMMAND_CUT"_ns; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: - return NS_LITERAL_CSTRING("APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE"); + return "APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE"_ns; case APPCOMMAND_FIND: - return NS_LITERAL_CSTRING("APPCOMMAND_FIND"); + return "APPCOMMAND_FIND"_ns; case APPCOMMAND_FORWARD_MAIL: - return NS_LITERAL_CSTRING("APPCOMMAND_FORWARD_MAIL"); + return "APPCOMMAND_FORWARD_MAIL"_ns; case APPCOMMAND_HELP: - return NS_LITERAL_CSTRING("APPCOMMAND_HELP"); + return "APPCOMMAND_HELP"_ns; case APPCOMMAND_LAUNCH_APP1: - return NS_LITERAL_CSTRING("APPCOMMAND_LAUNCH_APP1"); + return "APPCOMMAND_LAUNCH_APP1"_ns; case APPCOMMAND_LAUNCH_APP2: - return NS_LITERAL_CSTRING("APPCOMMAND_LAUNCH_APP2"); + return "APPCOMMAND_LAUNCH_APP2"_ns; case APPCOMMAND_LAUNCH_MAIL: - return NS_LITERAL_CSTRING("APPCOMMAND_LAUNCH_MAIL"); + return "APPCOMMAND_LAUNCH_MAIL"_ns; case APPCOMMAND_LAUNCH_MEDIA_SELECT: - return NS_LITERAL_CSTRING("APPCOMMAND_LAUNCH_MEDIA_SELECT"); + return "APPCOMMAND_LAUNCH_MEDIA_SELECT"_ns; case APPCOMMAND_MEDIA_CHANNEL_DOWN: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_CHANNEL_DOWN"); + return "APPCOMMAND_MEDIA_CHANNEL_DOWN"_ns; case APPCOMMAND_MEDIA_CHANNEL_UP: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_CHANNEL_UP"); + return "APPCOMMAND_MEDIA_CHANNEL_UP"_ns; case APPCOMMAND_MEDIA_FAST_FORWARD: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_FAST_FORWARD"); + return "APPCOMMAND_MEDIA_FAST_FORWARD"_ns; case APPCOMMAND_MEDIA_NEXTTRACK: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_NEXTTRACK"); + return "APPCOMMAND_MEDIA_NEXTTRACK"_ns; case APPCOMMAND_MEDIA_PAUSE: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_PAUSE"); + return "APPCOMMAND_MEDIA_PAUSE"_ns; case APPCOMMAND_MEDIA_PLAY: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_PLAY"); + return "APPCOMMAND_MEDIA_PLAY"_ns; case APPCOMMAND_MEDIA_PLAY_PAUSE: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_PLAY_PAUSE"); + return "APPCOMMAND_MEDIA_PLAY_PAUSE"_ns; case APPCOMMAND_MEDIA_PREVIOUSTRACK: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_PREVIOUSTRACK"); + return "APPCOMMAND_MEDIA_PREVIOUSTRACK"_ns; case APPCOMMAND_MEDIA_RECORD: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_RECORD"); + return "APPCOMMAND_MEDIA_RECORD"_ns; case APPCOMMAND_MEDIA_REWIND: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_REWIND"); + return "APPCOMMAND_MEDIA_REWIND"_ns; case APPCOMMAND_MEDIA_STOP: - return NS_LITERAL_CSTRING("APPCOMMAND_MEDIA_STOP"); + return "APPCOMMAND_MEDIA_STOP"_ns; case APPCOMMAND_MIC_ON_OFF_TOGGLE: - return NS_LITERAL_CSTRING("APPCOMMAND_MIC_ON_OFF_TOGGLE"); + return "APPCOMMAND_MIC_ON_OFF_TOGGLE"_ns; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: - return NS_LITERAL_CSTRING("APPCOMMAND_MICROPHONE_VOLUME_DOWN"); + return "APPCOMMAND_MICROPHONE_VOLUME_DOWN"_ns; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: - return NS_LITERAL_CSTRING("APPCOMMAND_MICROPHONE_VOLUME_MUTE"); + return "APPCOMMAND_MICROPHONE_VOLUME_MUTE"_ns; case APPCOMMAND_MICROPHONE_VOLUME_UP: - return NS_LITERAL_CSTRING("APPCOMMAND_MICROPHONE_VOLUME_UP"); + return "APPCOMMAND_MICROPHONE_VOLUME_UP"_ns; case APPCOMMAND_NEW: - return NS_LITERAL_CSTRING("APPCOMMAND_NEW"); + return "APPCOMMAND_NEW"_ns; case APPCOMMAND_OPEN: - return NS_LITERAL_CSTRING("APPCOMMAND_OPEN"); + return "APPCOMMAND_OPEN"_ns; case APPCOMMAND_PASTE: - return NS_LITERAL_CSTRING("APPCOMMAND_PASTE"); + return "APPCOMMAND_PASTE"_ns; case APPCOMMAND_PRINT: - return NS_LITERAL_CSTRING("APPCOMMAND_PRINT"); + return "APPCOMMAND_PRINT"_ns; case APPCOMMAND_REDO: - return NS_LITERAL_CSTRING("APPCOMMAND_REDO"); + return "APPCOMMAND_REDO"_ns; case APPCOMMAND_REPLY_TO_MAIL: - return NS_LITERAL_CSTRING("APPCOMMAND_REPLY_TO_MAIL"); + return "APPCOMMAND_REPLY_TO_MAIL"_ns; case APPCOMMAND_SAVE: - return NS_LITERAL_CSTRING("APPCOMMAND_SAVE"); + return "APPCOMMAND_SAVE"_ns; case APPCOMMAND_SEND_MAIL: - return NS_LITERAL_CSTRING("APPCOMMAND_SEND_MAIL"); + return "APPCOMMAND_SEND_MAIL"_ns; case APPCOMMAND_SPELL_CHECK: - return NS_LITERAL_CSTRING("APPCOMMAND_SPELL_CHECK"); + return "APPCOMMAND_SPELL_CHECK"_ns; case APPCOMMAND_TREBLE_DOWN: - return NS_LITERAL_CSTRING("APPCOMMAND_TREBLE_DOWN"); + return "APPCOMMAND_TREBLE_DOWN"_ns; case APPCOMMAND_TREBLE_UP: - return NS_LITERAL_CSTRING("APPCOMMAND_TREBLE_UP"); + return "APPCOMMAND_TREBLE_UP"_ns; case APPCOMMAND_UNDO: - return NS_LITERAL_CSTRING("APPCOMMAND_UNDO"); + return "APPCOMMAND_UNDO"_ns; case APPCOMMAND_VOLUME_DOWN: - return NS_LITERAL_CSTRING("APPCOMMAND_VOLUME_DOWN"); + return "APPCOMMAND_VOLUME_DOWN"_ns; case APPCOMMAND_VOLUME_MUTE: - return NS_LITERAL_CSTRING("APPCOMMAND_VOLUME_MUTE"); + return "APPCOMMAND_VOLUME_MUTE"_ns; case APPCOMMAND_VOLUME_UP: - return NS_LITERAL_CSTRING("APPCOMMAND_VOLUME_UP"); + return "APPCOMMAND_VOLUME_UP"_ns; default: return nsPrintfCString("Unknown app command (0x%08X)", aCommand); } @@ -677,11 +677,11 @@ static const nsCString GetAppCommandName(WPARAM aCommand) { static const nsCString GetAppCommandDeviceName(LPARAM aDevice) { switch (aDevice) { case FAPPCOMMAND_KEY: - return NS_LITERAL_CSTRING("FAPPCOMMAND_KEY"); + return "FAPPCOMMAND_KEY"_ns; case FAPPCOMMAND_MOUSE: - return NS_LITERAL_CSTRING("FAPPCOMMAND_MOUSE"); + return "FAPPCOMMAND_MOUSE"_ns; case FAPPCOMMAND_OEM: - return NS_LITERAL_CSTRING("FAPPCOMMAND_OEM"); + return "FAPPCOMMAND_OEM"_ns; default: return nsPrintfCString("Unknown app command device (0x%04X)", aDevice); } @@ -800,7 +800,7 @@ static const nsCString ToString(const MSG& aMSG) { static const nsCString ToString( const UniCharsAndModifiers& aUniCharsAndModifiers) { if (aUniCharsAndModifiers.IsEmpty()) { - return NS_LITERAL_CSTRING("{}"); + return "{}"_ns; } nsCString result; result.AssignLiteral("{ "); @@ -2931,7 +2931,7 @@ bool NativeKey::NeedsToHandleWithoutFollowingCharMessages() const { static nsCString GetResultOfInSendMessageEx() { DWORD ret = ::InSendMessageEx(nullptr); if (!ret) { - return NS_LITERAL_CSTRING("ISMEX_NOSEND"); + return "ISMEX_NOSEND"_ns; } nsCString result; if (ret & ISMEX_CALLBACK) { @@ -3225,7 +3225,7 @@ bool NativeKey::GetFollowingCharMessage(MSG& aCharMsg) { CrashReporter::AppendAppNotesToCrashReport(info); } else { CrashReporter::AppendAppNotesToCrashReport( - NS_LITERAL_CSTRING("\nThere is no message in any window")); + "\nThere is no message in any window"_ns); } MOZ_CRASH("We lost the following char message"); @@ -3374,8 +3374,8 @@ bool NativeKey::GetFollowingCharMessage(MSG& aCharMsg) { CrashReporter::AppendAppNotesToCrashReport(info); } else { CrashReporter::AppendAppNotesToCrashReport( - NS_LITERAL_CSTRING("\nThere is no key message after unexpected char " - "message removed, ")); + nsLiteralCString("\nThere is no key message after unexpected char " + "message removed, ")); } // Another window has a key message? if (WinUtils::PeekMessage(&nextKeyMsgInAllWindows, 0, WM_KEYFIRST, @@ -3385,7 +3385,7 @@ bool NativeKey::GetFollowingCharMessage(MSG& aCharMsg) { CrashReporter::AppendAppNotesToCrashReport(info); } else { CrashReporter::AppendAppNotesToCrashReport( - NS_LITERAL_CSTRING("\nThere is no key message in any windows.")); + "\nThere is no key message in any windows."_ns); } MOZ_CRASH("PeekMessage() removed unexpected message"); @@ -4341,7 +4341,7 @@ nsCString KeyboardLayout::GetLayoutName(HKL aLayout) const { wchar_t buf[256]; if (NS_WARN_IF(!WinUtils::GetRegistryKey( HKEY_LOCAL_MACHINE, key.get(), L"Layout Text", buf, sizeof(buf)))) { - return NS_LITERAL_CSTRING("No name or too long name"); + return "No name or too long name"_ns; } return NS_ConvertUTF16toUTF8(buf); } diff --git a/widget/windows/LSPAnnotator.cpp b/widget/windows/LSPAnnotator.cpp index 55856525319b..d0db086cd820 100644 --- a/widget/windows/LSPAnnotator.cpp +++ b/widget/windows/LSPAnnotator.cpp @@ -40,7 +40,7 @@ void LSPAnnotationGatherer::Annotate() { do_GetService("@mozilla.org/toolkit/crash-reporter;1"); bool enabled; if (cr && NS_SUCCEEDED(cr->GetEnabled(&enabled)) && enabled) { - cr->AnnotateCrashReport(NS_LITERAL_CSTRING("Winsock_LSP"), mString); + cr->AnnotateCrashReport("Winsock_LSP"_ns, mString); } } diff --git a/widget/windows/TSFTextStore.cpp b/widget/windows/TSFTextStore.cpp index 947be3c6b2eb..44b34e53eab4 100644 --- a/widget/windows/TSFTextStore.cpp +++ b/widget/windows/TSFTextStore.cpp @@ -214,9 +214,9 @@ static nsCString GetGUIDNameStr(REFGUID aGUID) { } static nsCString GetGUIDNameStrWithTable(REFGUID aGUID) { -#define RETURN_GUID_NAME(aNamedGUID) \ - if (IsEqualGUID(aGUID, aNamedGUID)) { \ - return NS_LITERAL_CSTRING(#aNamedGUID); \ +#define RETURN_GUID_NAME(aNamedGUID) \ + if (IsEqualGUID(aGUID, aNamedGUID)) { \ + return nsLiteralCString(#aNamedGUID); \ } RETURN_GUID_NAME(GUID_PROP_INPUTSCOPE) @@ -463,7 +463,7 @@ static const char* GetTextRunTypeName(TsRunType aRunType) { static nsCString GetColorName(const TF_DA_COLOR& aColor) { switch (aColor.type) { case TF_CT_NONE: - return NS_LITERAL_CSTRING("TF_CT_NONE"); + return "TF_CT_NONE"_ns; case TF_CT_SYSCOLOR: return nsPrintfCString("TF_CT_SYSCOLOR, nIndex:0x%08X", static_cast(aColor.nIndex)); @@ -480,15 +480,15 @@ static nsCString GetColorName(const TF_DA_COLOR& aColor) { static nsCString GetLineStyleName(TF_DA_LINESTYLE aLineStyle) { switch (aLineStyle) { case TF_LS_NONE: - return NS_LITERAL_CSTRING("TF_LS_NONE"); + return "TF_LS_NONE"_ns; case TF_LS_SOLID: - return NS_LITERAL_CSTRING("TF_LS_SOLID"); + return "TF_LS_SOLID"_ns; case TF_LS_DOT: - return NS_LITERAL_CSTRING("TF_LS_DOT"); + return "TF_LS_DOT"_ns; case TF_LS_DASH: - return NS_LITERAL_CSTRING("TF_LS_DASH"); + return "TF_LS_DASH"_ns; case TF_LS_SQUIGGLE: - return NS_LITERAL_CSTRING("TF_LS_SQUIGGLE"); + return "TF_LS_SQUIGGLE"_ns; default: { return nsPrintfCString("Unknown(%08X)", static_cast(aLineStyle)); } @@ -498,19 +498,19 @@ static nsCString GetLineStyleName(TF_DA_LINESTYLE aLineStyle) { static nsCString GetClauseAttrName(TF_DA_ATTR_INFO aAttr) { switch (aAttr) { case TF_ATTR_INPUT: - return NS_LITERAL_CSTRING("TF_ATTR_INPUT"); + return "TF_ATTR_INPUT"_ns; case TF_ATTR_TARGET_CONVERTED: - return NS_LITERAL_CSTRING("TF_ATTR_TARGET_CONVERTED"); + return "TF_ATTR_TARGET_CONVERTED"_ns; case TF_ATTR_CONVERTED: - return NS_LITERAL_CSTRING("TF_ATTR_CONVERTED"); + return "TF_ATTR_CONVERTED"_ns; case TF_ATTR_TARGET_NOTCONVERTED: - return NS_LITERAL_CSTRING("TF_ATTR_TARGET_NOTCONVERTED"); + return "TF_ATTR_TARGET_NOTCONVERTED"_ns; case TF_ATTR_INPUT_ERROR: - return NS_LITERAL_CSTRING("TF_ATTR_INPUT_ERROR"); + return "TF_ATTR_INPUT_ERROR"_ns; case TF_ATTR_FIXEDCONVERTED: - return NS_LITERAL_CSTRING("TF_ATTR_FIXEDCONVERTED"); + return "TF_ATTR_FIXEDCONVERTED"_ns; case TF_ATTR_OTHER: - return NS_LITERAL_CSTRING("TF_ATTR_OTHER"); + return "TF_ATTR_OTHER"_ns; default: { return nsPrintfCString("Unknown(%08X)", static_cast(aAttr)); } @@ -554,7 +554,7 @@ static const char* GetMouseButtonName(int16_t aButton) { static nsCString GetMouseButtonsName(int16_t aButtons) { if (!aButtons) { - return NS_LITERAL_CSTRING("no buttons"); + return "no buttons"_ns; } nsCString names; if (aButtons & MouseButtonsFlag::ePrimaryFlag) { @@ -581,7 +581,7 @@ static nsCString GetMouseButtonsName(int16_t aButtons) { static nsCString GetModifiersName(Modifiers aModifiers) { if (aModifiers == MODIFIER_NONE) { - return NS_LITERAL_CSTRING("no modifiers"); + return "no modifiers"_ns; } nsCString names; if (aModifiers & MODIFIER_ALT) { @@ -1200,8 +1200,7 @@ class TSFStaticSink final : public ITfInputProcessorProfileActivationSink { EnsureInitActiveTIPKeyboard(); // FYI: Name of packaged ATOK includes the release year like "ATOK 2015". // Name of ATOK Passport (subscription) equals "ATOK". - return StringBeginsWith(mActiveTIPKeyboardDescription, - NS_LITERAL_STRING("ATOK ")) || + return StringBeginsWith(mActiveTIPKeyboardDescription, u"ATOK "_ns) || mActiveTIPKeyboardDescription.EqualsLiteral("ATOK"); } diff --git a/widget/windows/ToastNotificationHandler.cpp b/widget/windows/ToastNotificationHandler.cpp index cf3087e9091e..923b6da38e9f 100644 --- a/widget/windows/ToastNotificationHandler.cpp +++ b/widget/windows/ToastNotificationHandler.cpp @@ -101,7 +101,7 @@ static bool AddActionNode(IXmlDocument* toastXml, IXmlNode* actionsNode, } if (NS_WARN_IF(!SetAttribute(action.Get(), HStringReference(L"placement").Get(), - NS_LITERAL_STRING("contextmenu")))) { + u"contextmenu"_ns))) { return false; } @@ -314,7 +314,7 @@ bool ToastNotificationHandler::ShowAlert() { if (SUCCEEDED(hr)) { // placement is supported on Windows 10 Anniversary Update or later SetAttribute(placementText.Get(), HStringReference(L"placement").Get(), - NS_LITERAL_STRING("attribution")); + u"attribution"_ns); } } @@ -323,13 +323,13 @@ bool ToastNotificationHandler::ShowAlert() { formatStrings, disableButtonTitle); AddActionNode(toastXml.Get(), actionsNode.Get(), disableButtonTitle, - NS_LITERAL_STRING("snooze")); + u"snooze"_ns); } nsAutoString settingsButtonTitle; bundle->GetStringFromName("webActions.settings.label", settingsButtonTitle); AddActionNode(toastXml.Get(), actionsNode.Get(), settingsButtonTitle, - NS_LITERAL_STRING("settings")); + u"settings"_ns); ComPtr appendedChild; hr = toastNodeRoot->AppendChild(actionsNode.Get(), &appendedChild); @@ -523,7 +523,7 @@ nsresult ToastNotificationHandler::AsyncSaveImage(imgIRequest* aRequest) { return rv; } - rv = mImageFile->Append(NS_LITERAL_STRING("notificationimages")); + rv = mImageFile->Append(u"notificationimages"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/widget/windows/WinIMEHandler.cpp b/widget/windows/WinIMEHandler.cpp index d5ce5c38f6ca..ae6962e7dbc8 100644 --- a/widget/windows/WinIMEHandler.cpp +++ b/widget/windows/WinIMEHandler.cpp @@ -1023,7 +1023,7 @@ bool IMEHandler::AutoInvokeOnScreenKeyboardInDesktopMode() { return false; } rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("SOFTWARE\\Microsoft\\TabletTip\\1.7"), + u"SOFTWARE\\Microsoft\\TabletTip\\1.7"_ns, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) { Preferences::SetString(kOskDebugReason, @@ -1035,8 +1035,7 @@ bool IMEHandler::AutoInvokeOnScreenKeyboardInDesktopMode() { // when there's no keyboard attached to your device." If the user has // opted-in to this behavior, the tablet-mode requirement is skipped. uint32_t value; - rv = regKey->ReadIntValue(NS_LITERAL_STRING("EnableDesktopModeAutoInvoke"), - &value); + rv = regKey->ReadIntValue(u"EnableDesktopModeAutoInvoke"_ns, &value); if (NS_FAILED(rv)) { Preferences::SetString(kOskDebugReason, L"AIOSKIDM: failed reading value of regkey."); diff --git a/widget/windows/WinUtils.cpp b/widget/windows/WinUtils.cpp index 7892dbd72878..1788f29cd7c4 100644 --- a/widget/windows/WinUtils.cpp +++ b/widget/windows/WinUtils.cpp @@ -2063,14 +2063,14 @@ bool WinUtils::UnexpandEnvVars(nsAString& aPath) { WinUtils::WhitelistVec WinUtils::BuildWhitelist() { WhitelistVec result; - Unused << result.emplaceBack(std::make_pair( - nsString(NS_LITERAL_STRING("%ProgramFiles%")), nsDependentString())); + Unused << result.emplaceBack( + std::make_pair(nsString(u"%ProgramFiles%"_ns), nsDependentString())); // When no substitution is required, set the void flag result.back().second.SetIsVoid(true); - Unused << result.emplaceBack(std::make_pair( - nsString(NS_LITERAL_STRING("%SystemRoot%")), nsDependentString())); + Unused << result.emplaceBack( + std::make_pair(nsString(u"%SystemRoot%"_ns), nsDependentString())); result.back().second.SetIsVoid(true); wchar_t tmpPath[MAX_PATH + 1] = {}; diff --git a/widget/windows/WindowsSMTCProvider.cpp b/widget/windows/WindowsSMTCProvider.cpp index c6b7631c5f77..23ef82748afc 100644 --- a/widget/windows/WindowsSMTCProvider.cpp +++ b/widget/windows/WindowsSMTCProvider.cpp @@ -477,7 +477,7 @@ void WindowsSMTCProvider::LoadImageAtIndex(const size_t aIndex) { // image, we can use `CreateFromFile` to create the IRandomAccessStream. We // should probably cache it since it could be used very often (Bug 1643102) - if (image.mSrc.Find(NS_LITERAL_CSTRING("file:///"), false, 0, 0) == 0) { + if (image.mSrc.Find("file:///"_ns, false, 0, 0) == 0) { LOG("Skip the local file. Try next"); mImageFetchRequest.DisconnectIfExists(); LoadImageAtIndex(aIndex + 1); @@ -505,7 +505,7 @@ void WindowsSMTCProvider::LoadImageAtIndex(const size_t aIndex) { // Only used to hold the image data nsCOMPtr inputStream; nsresult rv = - GetEncodedImageBuffer(aImage, NS_LITERAL_CSTRING(IMAGE_PNG), + GetEncodedImageBuffer(aImage, nsLiteralCString(IMAGE_PNG), getter_AddRefs(inputStream), &size, &src); if (NS_FAILED(rv) || !inputStream || size == 0 || !src) { LOG("Failed to get the image buffer info"); diff --git a/widget/windows/WindowsUIUtils.cpp b/widget/windows/WindowsUIUtils.cpp index e9574a53e447..c07dabb49621 100644 --- a/widget/windows/WindowsUIUtils.cpp +++ b/widget/windows/WindowsUIUtils.cpp @@ -365,10 +365,9 @@ RefPtr WindowsUIUtils::Share(nsAutoString aTitle, * Thus we trick the API by passing a whitespace when we have no title. * https://docs.microsoft.com/en-us/windows/uwp/app-to-app/share-data */ - auto wTitle = - ConvertToWindowsString((title.IsVoid() || title.Length() == 0) - ? nsAutoString(NS_LITERAL_STRING(" ")) - : title); + auto wTitle = ConvertToWindowsString((title.IsVoid() || title.Length() == 0) + ? nsAutoString(u" "_ns) + : title); if (wTitle.isErr() || FAILED(spDataPackageProperties->put_Title(wTitle.unwrap().get()))) { promiseHolder->Reject(NS_ERROR_FAILURE, __func__); diff --git a/widget/windows/nsAppShell.cpp b/widget/windows/nsAppShell.cpp index 566b3508e310..062470db6110 100644 --- a/widget/windows/nsAppShell.cpp +++ b/widget/windows/nsAppShell.cpp @@ -297,7 +297,7 @@ nsAppShell::Observe(nsISupports* aSubject, const char* aTopic, !gUiaHook) { nsDependentString dllName(aData); - if (StringEndsWith(dllName, NS_LITERAL_STRING("uiautomationcore.dll"), + if (StringEndsWith(dllName, u"uiautomationcore.dll"_ns, nsCaseInsensitiveStringComparator)) { InitUIADetection(); diff --git a/widget/windows/nsClipboard.cpp b/widget/windows/nsClipboard.cpp index 567f7857946e..92fca872a76b 100644 --- a/widget/windows/nsClipboard.cpp +++ b/widget/windows/nsClipboard.cpp @@ -470,7 +470,7 @@ nsresult nsClipboard::GetNativeDataOffClipboard(IDataObject* aDataObject, do_CreateInstance("@mozilla.org/image/tools;1"); result = imgTools->DecodeImageFromBuffer( clipboardData, allocLen, - NS_LITERAL_CSTRING(IMAGE_BMP_MS_CLIPBOARD), + nsLiteralCString(IMAGE_BMP_MS_CLIPBOARD), getter_AddRefs(container)); if (NS_FAILED(result)) { break; @@ -880,7 +880,7 @@ bool nsClipboard ::FindURLFromLocalFile(IDataObject* inDataObject, UINT inIndex, if (title.IsEmpty()) { title = urlString; } - *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + title); + *outData = ToNewUnicode(urlString + u"\n"_ns + title); *outDataLen = NS_strlen(static_cast(*outData)) * sizeof(char16_t); @@ -925,7 +925,7 @@ bool nsClipboard ::FindURLFromNativeURL(IDataObject* inDataObject, UINT inIndex, // the internal mozilla URL format, text/x-moz-url, contains // URL\ntitle. Since we don't actually have a title here, // just repeat the URL to fake it. - *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + urlString); + *outData = ToNewUnicode(urlString + u"\n"_ns + urlString); *outDataLen = NS_strlen(static_cast(*outData)) * sizeof(char16_t); free(tempOutData); @@ -954,7 +954,7 @@ bool nsClipboard ::FindURLFromNativeURL(IDataObject* inDataObject, UINT inIndex, // the internal mozilla URL format, text/x-moz-url, contains // URL\ntitle. Since we don't actually have a title here, // just repeat the URL to fake it. - *outData = ToNewUnicode(urlString + NS_LITERAL_STRING("\n") + urlString); + *outData = ToNewUnicode(urlString + u"\n"_ns + urlString); *outDataLen = NS_strlen(static_cast(*outData)) * sizeof(char16_t); free(tempOutData); @@ -990,7 +990,7 @@ void nsClipboard ::ResolveShortcut(nsIFile* aFile, nsACString& outURL) { // A file is an Internet Shortcut if it ends with .URL // bool nsClipboard ::IsInternetShortcut(const nsAString& inFileName) { - return StringEndsWith(inFileName, NS_LITERAL_STRING(".url"), + return StringEndsWith(inFileName, u".url"_ns, nsCaseInsensitiveStringComparator); } // IsInternetShortcut diff --git a/widget/windows/nsDataObj.cpp b/widget/windows/nsDataObj.cpp index 780020e2869d..bb082b541fa4 100644 --- a/widget/windows/nsDataObj.cpp +++ b/widget/windows/nsDataObj.cpp @@ -477,8 +477,7 @@ nsDataObj::nsDataObj(nsIURI* uri) mTransferable(nullptr), mIsAsyncMode(FALSE), mIsInOperation(FALSE) { - mIOThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, - NS_LITERAL_CSTRING("nsDataObj"), + mIOThread = new LazyIdleThread(DEFAULT_THREAD_TIMEOUT_MS, "nsDataObj"_ns, LazyIdleThread::ManualShutdown); m_enumFE = new CEnumFormatEtc(); m_enumFE->AddRef(); @@ -958,7 +957,7 @@ nsDataObj::GetDib(const nsACString& inFlavor, FORMATETC& aFormat, nsCOMPtr imgTools = do_CreateInstance("@mozilla.org/image/tools;1"); - nsAutoString options(NS_LITERAL_STRING("bpp=32;")); + nsAutoString options(u"bpp=32;"_ns); if (aFormat.cfFormat == CF_DIBV5) { options.AppendLiteral("version=5"); } else { @@ -966,7 +965,7 @@ nsDataObj::GetDib(const nsACString& inFlavor, FORMATETC& aFormat, } nsCOMPtr inputStream; - nsresult rv = imgTools->EncodeImage(image, NS_LITERAL_CSTRING(IMAGE_BMP), + nsresult rv = imgTools->EncodeImage(image, nsLiteralCString(IMAGE_BMP), options, getter_AddRefs(inputStream)); if (NS_FAILED(rv) || !inputStream) { return E_FAIL; @@ -1612,8 +1611,8 @@ HRESULT nsDataObj::DropImage(FORMATETC& aFE, STGMEDIUM& aSTG) { nsCOMPtr imgTools = do_CreateInstance("@mozilla.org/image/tools;1"); nsCOMPtr inputStream; - rv = imgTools->EncodeImage(image, NS_LITERAL_CSTRING(IMAGE_BMP), - NS_LITERAL_STRING("bpp=32;version=3"), + rv = imgTools->EncodeImage(image, nsLiteralCString(IMAGE_BMP), + u"bpp=32;version=3"_ns, getter_AddRefs(inputStream)); if (NS_FAILED(rv) || !inputStream) { return E_FAIL; diff --git a/widget/windows/nsDeviceContextSpecWin.cpp b/widget/windows/nsDeviceContextSpecWin.cpp index 96d55c1db2fa..f94382f2c28c 100644 --- a/widget/windows/nsDeviceContextSpecWin.cpp +++ b/widget/windows/nsDeviceContextSpecWin.cpp @@ -151,45 +151,38 @@ NS_IMETHODIMP nsDeviceContextSpecWin::Init(nsIWidget* aWidget, // novaPDF, PDF-XChange and Soda PDF, for example.) if (mOutputFormat == nsIPrintSettings::kOutputFormatPDF) { Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, - NS_LITERAL_STRING("pdf_file"), 1); - } else if (StringBeginsWith(printerName, - NS_LITERAL_STRING("Microsoft Print to PDF")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("Adobe PDF")) || + u"pdf_file"_ns, 1); + } else if (StringBeginsWith(printerName, u"Microsoft Print to PDF"_ns) || + StringBeginsWith(printerName, u"Adobe PDF"_ns) || + StringBeginsWith(printerName, u"Bullzip PDF Printer"_ns) || + StringBeginsWith(printerName, u"CutePDF Writer"_ns) || + StringBeginsWith(printerName, u"doPDF"_ns) || + StringBeginsWith(printerName, u"Foxit Reader PDF Printer"_ns) || + StringBeginsWith(printerName, u"Nitro PDF Creator"_ns) || + StringBeginsWith(printerName, u"novaPDF"_ns) || + StringBeginsWith(printerName, u"PDF-XChange"_ns) || + StringBeginsWith(printerName, u"PDF24 PDF"_ns) || + StringBeginsWith(printerName, u"PDFCreator"_ns) || + StringBeginsWith(printerName, u"PrimoPDF"_ns) || + StringBeginsWith(printerName, u"Soda PDF"_ns) || + StringBeginsWith(printerName, u"Solid PDF Creator"_ns) || StringBeginsWith(printerName, - NS_LITERAL_STRING("Bullzip PDF Printer")) || - StringBeginsWith(printerName, - NS_LITERAL_STRING("CutePDF Writer")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("doPDF")) || - StringBeginsWith(printerName, - NS_LITERAL_STRING("Foxit Reader PDF Printer")) || - StringBeginsWith(printerName, - NS_LITERAL_STRING("Nitro PDF Creator")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("novaPDF")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("PDF-XChange")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("PDF24 PDF")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("PDFCreator")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("PrimoPDF")) || - StringBeginsWith(printerName, NS_LITERAL_STRING("Soda PDF")) || - StringBeginsWith(printerName, - NS_LITERAL_STRING("Solid PDF Creator")) || - StringBeginsWith( - printerName, - NS_LITERAL_STRING("Universal Document Converter"))) { + u"Universal Document Converter"_ns)) { Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, - NS_LITERAL_STRING("pdf_file"), 1); + u"pdf_file"_ns, 1); } else if (printerName.EqualsLiteral("Microsoft XPS Document Writer")) { Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, - NS_LITERAL_STRING("xps_file"), 1); + u"xps_file"_ns, 1); } else { nsAString::const_iterator start, end; printerName.BeginReading(start); printerName.EndReading(end); - if (CaseInsensitiveFindInReadable(NS_LITERAL_STRING("pdf"), start, end)) { + if (CaseInsensitiveFindInReadable(u"pdf"_ns, start, end)) { Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, - NS_LITERAL_STRING("pdf_unknown"), 1); + u"pdf_unknown"_ns, 1); } else { Telemetry::ScalarAdd(Telemetry::ScalarID::PRINTING_TARGET_TYPE, - NS_LITERAL_STRING("unknown"), 1); + u"unknown"_ns, 1); } } diff --git a/widget/windows/nsFilePicker.cpp b/widget/windows/nsFilePicker.cpp index 733518fc9b54..605b79611ebf 100644 --- a/widget/windows/nsFilePicker.cpp +++ b/widget/windows/nsFilePicker.cpp @@ -703,9 +703,8 @@ bool nsFilePicker::IsDefaultPathLink() { NS_ConvertUTF16toUTF8 ext(mDefaultFilePath); ext.Trim(" .", false, true); // watch out for trailing space and dots ToLowerCase(ext); - if (StringEndsWith(ext, NS_LITERAL_CSTRING(".lnk")) || - StringEndsWith(ext, NS_LITERAL_CSTRING(".pif")) || - StringEndsWith(ext, NS_LITERAL_CSTRING(".url"))) + if (StringEndsWith(ext, ".lnk"_ns) || StringEndsWith(ext, ".pif"_ns) || + StringEndsWith(ext, ".url"_ns)) return true; return false; } diff --git a/widget/windows/nsLookAndFeel.cpp b/widget/windows/nsLookAndFeel.cpp index 3f43d11d9968..126751f49178 100644 --- a/widget/windows/nsLookAndFeel.cpp +++ b/widget/windows/nsLookAndFeel.cpp @@ -71,16 +71,16 @@ static nsresult SystemWantsDarkTheme(int32_t& darkThemeEnabled) { rv = personalizeKey->Open( nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING( - "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), + nsLiteralString( + u"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_FAILED(rv)) { return rv; } uint32_t lightThemeEnabled; - rv = personalizeKey->ReadIntValue(NS_LITERAL_STRING("AppsUseLightTheme"), - &lightThemeEnabled); + rv = + personalizeKey->ReadIntValue(u"AppsUseLightTheme"_ns, &lightThemeEnabled); if (NS_SUCCEEDED(rv)) { darkThemeEnabled = !lightThemeEnabled; } @@ -488,10 +488,9 @@ nsresult nsLookAndFeel::GetIntImpl(IntID aID, int32_t& aResult) { } uint32_t colorPrevalence; - nsresult rv = - mDwmKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("SOFTWARE\\Microsoft\\Windows\\DWM"), - nsIWindowsRegKey::ACCESS_QUERY_VALUE); + nsresult rv = mDwmKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, + u"SOFTWARE\\Microsoft\\Windows\\DWM"_ns, + nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -499,8 +498,8 @@ nsresult nsLookAndFeel::GetIntImpl(IntID aID, int32_t& aResult) { // The ColorPrevalence value is set to 1 when the "Show color on title // bar" setting in the Color section of Window's Personalization settings // is turned on. - aResult = (NS_SUCCEEDED(mDwmKey->ReadIntValue( - NS_LITERAL_STRING("ColorPrevalence"), &colorPrevalence)) && + aResult = (NS_SUCCEEDED(mDwmKey->ReadIntValue(u"ColorPrevalence"_ns, + &colorPrevalence)) && colorPrevalence == 1) ? 1 : 0; @@ -738,7 +737,7 @@ static bool GetSysFontInfo(HDC aHDC, LookAndFeel::FontID anID, aFontStyle.systemFont = true; if (useShellDlg) { - aFontName = NS_LITERAL_STRING("MS Shell Dlg 2"); + aFontName = u"MS Shell Dlg 2"_ns; } else { memcpy(name, ptrLogFont->lfFaceName, LF_FACESIZE * sizeof(char16_t)); aFontName = name; @@ -831,15 +830,14 @@ nsresult nsLookAndFeel::GetAccentColor(nscolor& aColor) { } rv = mDwmKey->Open(nsIWindowsRegKey::ROOT_KEY_CURRENT_USER, - NS_LITERAL_STRING("SOFTWARE\\Microsoft\\Windows\\DWM"), + u"SOFTWARE\\Microsoft\\Windows\\DWM"_ns, nsIWindowsRegKey::ACCESS_QUERY_VALUE); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } uint32_t accentColor; - if (NS_SUCCEEDED(mDwmKey->ReadIntValue(NS_LITERAL_STRING("AccentColor"), - &accentColor))) { + if (NS_SUCCEEDED(mDwmKey->ReadIntValue(u"AccentColor"_ns, &accentColor))) { // The order of the color components in the DWORD stored in the registry // happens to be the same order as we store the components in nscolor // so we can just assign directly here. diff --git a/widget/windows/nsWindow.cpp b/widget/windows/nsWindow.cpp index 5719920e58cd..d1435eaec2de 100644 --- a/widget/windows/nsWindow.cpp +++ b/widget/windows/nsWindow.cpp @@ -3685,8 +3685,7 @@ void nsWindow::SetIcon(const nsAString& aIconSpec) { // Assume the given string is a local identifier for an icon file. nsCOMPtr iconFile; - ResolveIconName(aIconSpec, NS_LITERAL_STRING(".ico"), - getter_AddRefs(iconFile)); + ResolveIconName(aIconSpec, u".ico"_ns, getter_AddRefs(iconFile)); if (!iconFile) return; nsAutoString iconPath; @@ -4352,8 +4351,7 @@ bool nsWindow::TouchEventShouldStartDrag(EventMessage aEventMessage, for (Element* element = content->GetAsElementOrParentElement(); element; element = element->GetParentElement()) { nsAutoString startDrag; - element->GetAttribute(NS_LITERAL_STRING("touchdownstartsdrag"), - startDrag); + element->GetAttribute(u"touchdownstartsdrag"_ns, startDrag); if (!startDrag.IsEmpty()) { return true; } @@ -5967,7 +5965,7 @@ bool nsWindow::ProcessMessage(UINT msg, WPARAM& wParam, LPARAM& lParam, // actual mousedown event because that would break dragging or interfere // with other mousedown handling in the caption area. if (WithinDraggableRegion(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))) { - DispatchCustomEvent(NS_LITERAL_STRING("draggableregionleftmousedown")); + DispatchCustomEvent(u"draggableregionleftmousedown"_ns); } break; } diff --git a/xpcom/base/CycleCollectedJSContext.cpp b/xpcom/base/CycleCollectedJSContext.cpp index 33bcdef29db4..6ca3190c109d 100644 --- a/xpcom/base/CycleCollectedJSContext.cpp +++ b/xpcom/base/CycleCollectedJSContext.cpp @@ -352,8 +352,8 @@ void CycleCollectedJSContext::PromiseRejectionTrackerCallback( init.mReason = JS::GetPromiseResult(aPromise); RefPtr event = - PromiseRejectionEvent::Constructor( - owner, NS_LITERAL_STRING("rejectionhandled"), init); + PromiseRejectionEvent::Constructor(owner, u"rejectionhandled"_ns, + init); RefPtr asyncDispatcher = new AsyncEventDispatcher(owner, event); @@ -712,8 +712,8 @@ NS_IMETHODIMP CycleCollectedJSContext::NotifyUnhandledRejections::Run() { init.mCancelable = true; RefPtr event = - PromiseRejectionEvent::Constructor( - target, NS_LITERAL_STRING("unhandledrejection"), init); + PromiseRejectionEvent::Constructor(target, u"unhandledrejection"_ns, + init); // We don't use the result of dispatching event here to check whether to // report the Promise to console. target->DispatchEvent(*event); diff --git a/xpcom/base/LogCommandLineHandler.cpp b/xpcom/base/LogCommandLineHandler.cpp index 89aa4e8ec685..7bb149ce5b9c 100644 --- a/xpcom/base/LogCommandLineHandler.cpp +++ b/xpcom/base/LogCommandLineHandler.cpp @@ -19,8 +19,7 @@ void LoggingHandleCommandLineArgs( // Used for the `-MOZ_LOG ` form of argument. nsAutoCString env; - auto const names = {NS_LITERAL_CSTRING("MOZ_LOG"), - NS_LITERAL_CSTRING("MOZ_LOG_FILE")}; + auto const names = {"MOZ_LOG"_ns, "MOZ_LOG_FILE"_ns}; for (int arg = 1; arg < argc; ++arg) { Tokenizer p(argv[arg]); diff --git a/xpcom/base/nsCycleCollector.cpp b/xpcom/base/nsCycleCollector.cpp index 348ec8ae123f..352c28de4d83 100644 --- a/xpcom/base/nsCycleCollector.cpp +++ b/xpcom/base/nsCycleCollector.cpp @@ -1412,7 +1412,7 @@ class nsCycleCollectorLogSinkToFile final : public nsICycleCollectorLogSink { if (!mGCLog.mStream) { return NS_ERROR_UNEXPECTED; } - CloseLog(&mGCLog, NS_LITERAL_STRING("Garbage")); + CloseLog(&mGCLog, u"Garbage"_ns); return NS_OK; } @@ -1420,7 +1420,7 @@ class nsCycleCollectorLogSinkToFile final : public nsICycleCollectorLogSink { if (!mCCLog.mStream) { return NS_ERROR_UNEXPECTED; } - CloseLog(&mCCLog, NS_LITERAL_STRING("Cycle")); + CloseLog(&mCCLog, u"Cycle"_ns); return NS_OK; } @@ -1470,8 +1470,8 @@ class nsCycleCollectorLogSinkToFile final : public nsICycleCollectorLogSink { // aFilename under a memory-reporting-specific folder // (/data/local/tmp/memory-reports). Otherwise, it will open a // file named aFilename under "NS_OS_TEMP_DIR". - nsresult rv = nsDumpUtils::OpenTempFile( - filename, &logFile, NS_LITERAL_CSTRING("memory-reports")); + nsresult rv = + nsDumpUtils::OpenTempFile(filename, &logFile, "memory-reports"_ns); if (NS_FAILED(rv)) { NS_IF_RELEASE(logFile); return nullptr; @@ -1532,8 +1532,8 @@ class nsCycleCollectorLogSinkToFile final : public nsICycleCollectorLogSink { // Log to the error console. nsAutoString logPath; logFileFinalDestination->GetPath(logPath); - nsAutoString msg = aCollectorKind + - NS_LITERAL_STRING(" Collector log dumped to ") + logPath; + nsAutoString msg = + aCollectorKind + u" Collector log dumped to "_ns + logPath; // We don't want any JS to run between ScanRoots and CollectWhite calls, // and since ScanRoots calls this method, better to log the message diff --git a/xpcom/base/nsDumpUtils.cpp b/xpcom/base/nsDumpUtils.cpp index 5085e25bd022..6be0b88f0efa 100644 --- a/xpcom/base/nsDumpUtils.cpp +++ b/xpcom/base/nsDumpUtils.cpp @@ -292,7 +292,7 @@ int FifoWatcher::OpenFd() { } } - rv = file->AppendNative(NS_LITERAL_CSTRING("debug_info_trigger")); + rv = file->AppendNative("debug_info_trigger"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return -1; } diff --git a/xpcom/base/nsIMemoryReporter.idl b/xpcom/base/nsIMemoryReporter.idl index f51305186c63..dde543bd5b74 100644 --- a/xpcom/base/nsIMemoryReporter.idl +++ b/xpcom/base/nsIMemoryReporter.idl @@ -611,8 +611,8 @@ nsresult RegisterNonJSSizeOfTab(NonJSSizeOfTabFn aSizeOfTabFn); // variables. The (void) is there because we should always ignore the return // value of the callback, because callback failures aren't fatal. #define MOZ_COLLECT_REPORT(path, kind, units, amount, description) \ - (void)aHandleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(path), \ + (void)aHandleReport->Callback(EmptyCString(), nsLiteralCString(path), \ kind, units, amount, \ - NS_LITERAL_CSTRING(description), aData) + nsLiteralCString(description), aData) %} diff --git a/xpcom/base/nsMacUtilsImpl.cpp b/xpcom/base/nsMacUtilsImpl.cpp index fbf87f2c1b62..06b919afcb79 100644 --- a/xpcom/base/nsMacUtilsImpl.cpp +++ b/xpcom/base/nsMacUtilsImpl.cpp @@ -172,7 +172,7 @@ bool nsMacUtilsImpl::GetAppPath(nsCString& aAppPath) { // The binary path resides within the .app dir in Contents/MacOS, // e.g., Firefox.app/Contents/MacOS/firefox. Search backwards in // the binary path for the end of .app path. - auto pattern = NS_LITERAL_CSTRING("/Contents/MacOS/"); + auto pattern = "/Contents/MacOS/"_ns; nsAutoCString::const_iterator start, end; appBinaryPath.BeginReading(start); appBinaryPath.EndReading(end); diff --git a/xpcom/base/nsMemoryInfoDumper.cpp b/xpcom/base/nsMemoryInfoDumper.cpp index 54765f41bfa0..ecbb6171d3e9 100644 --- a/xpcom/base/nsMemoryInfoDumper.cpp +++ b/xpcom/base/nsMemoryInfoDumper.cpp @@ -214,12 +214,11 @@ bool SetupFifo() { FifoWatcher* fw = FifoWatcher::GetSingleton(); // Dump our memory reports (but run this on the main thread!). - fw->RegisterCallback(NS_LITERAL_CSTRING("memory report"), doMemoryReport); - fw->RegisterCallback(NS_LITERAL_CSTRING("minimize memory report"), - doMemoryReport); + fw->RegisterCallback("memory report"_ns, doMemoryReport); + fw->RegisterCallback("minimize memory report"_ns, doMemoryReport); // Dump GC and CC logs (from the main thread). - fw->RegisterCallback(NS_LITERAL_CSTRING("gc log"), doGCCCDump); - fw->RegisterCallback(NS_LITERAL_CSTRING("abbreviated gc log"), doGCCCDump); + fw->RegisterCallback("gc log"_ns, doGCCCDump); + fw->RegisterCallback("abbreviated gc log"_ns, doGCCCDump); # ifdef DEBUG fifoCallbacksRegistered = true; @@ -521,7 +520,7 @@ class TempDirFinishCallback final : public nsIFinishDumpingCallback { } #ifdef ANDROID - rv = reportsFinalFile->AppendNative(NS_LITERAL_CSTRING("memory-reports")); + rv = reportsFinalFile->AppendNative("memory-reports"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -562,7 +561,7 @@ class TempDirFinishCallback final : public nsIFinishDumpingCallback { return rv; } - nsString msg = NS_LITERAL_STRING("nsIMemoryInfoDumper dumped reports to "); + nsString msg = u"nsIMemoryInfoDumper dumped reports to "_ns; msg.Append(path); return cs->LogStringMessage(msg.get()); } @@ -683,9 +682,9 @@ nsMemoryInfoDumper::DumpMemoryInfoToTempDir(const nsAString& aIdentifier, // In Android case, this function will open a file named aFilename under // specific folder (/data/local/tmp/memory-reports). Otherwise, it will // open a file named aFilename under "NS_OS_TEMP_DIR". - rv = nsDumpUtils::OpenTempFile( - NS_LITERAL_CSTRING("incomplete-") + reportsFinalFilename, - getter_AddRefs(reportsTmpFile), NS_LITERAL_CSTRING("memory-reports")); + rv = nsDumpUtils::OpenTempFile("incomplete-"_ns + reportsFinalFilename, + getter_AddRefs(reportsTmpFile), + "memory-reports"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -720,7 +719,7 @@ nsresult nsMemoryInfoDumper::OpenDMDFile(const nsAString& aIdentifier, int aPid, nsresult rv; nsCOMPtr dmdFile; rv = nsDumpUtils::OpenTempFile(dmdFilename, getter_AddRefs(dmdFile), - NS_LITERAL_CSTRING("memory-reports")); + "memory-reports"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/xpcom/base/nsMemoryReporterManager.cpp b/xpcom/base/nsMemoryReporterManager.cpp index 6aca7a68571f..8464515561f2 100644 --- a/xpcom/base/nsMemoryReporterManager.cpp +++ b/xpcom/base/nsMemoryReporterManager.cpp @@ -880,9 +880,9 @@ class WindowsAddressSpaceReporter final : public nsIMemoryReporter { // Append the segment count. path.AppendPrintf("(segments=%u)", entry->mCount); - aHandleReport->Callback( - EmptyCString(), path, KIND_OTHER, UNITS_BYTES, entry->mSize, - NS_LITERAL_CSTRING("From MEMORY_BASIC_INFORMATION."), aData); + aHandleReport->Callback(EmptyCString(), path, KIND_OTHER, UNITS_BYTES, + entry->mSize, "From MEMORY_BASIC_INFORMATION."_ns, + aData); } return NS_OK; @@ -1409,8 +1409,8 @@ class ThreadsReporter final : public nsIMemoryReporter { aHandleReport->Callback( EmptyCString(), path, KIND_NONHEAP, UNITS_BYTES, thread.mPrivateSize, - NS_LITERAL_CSTRING("The sizes of thread stacks which have been " - "committed to memory."), + nsLiteralCString("The sizes of thread stacks which have been " + "committed to memory."), aData); } diff --git a/xpcom/base/nsSystemInfo.cpp b/xpcom/base/nsSystemInfo.cpp index 17d3f4a03018..57266285f5a6 100644 --- a/xpcom/base/nsSystemInfo.cpp +++ b/xpcom/base/nsSystemInfo.cpp @@ -709,12 +709,12 @@ nsresult CollectProcessInfo(ProcessInfo& info) { SimpleParseKeyValuePairs("/proc/cpuinfo", keyValuePairs); // cpuVendor from "vendor_id" - info.cpuVendor.Assign(keyValuePairs[NS_LITERAL_CSTRING("vendor_id")]); + info.cpuVendor.Assign(keyValuePairs["vendor_id"_ns]); { // cpuFamily from "cpu family" Tokenizer::Token t; - Tokenizer p(keyValuePairs[NS_LITERAL_CSTRING("cpu family")]); + Tokenizer p(keyValuePairs["cpu family"_ns]); if (p.Next(t) && t.Type() == Tokenizer::TOKEN_INTEGER && t.AsInteger() <= INT32_MAX) { cpuFamily = static_cast(t.AsInteger()); @@ -724,7 +724,7 @@ nsresult CollectProcessInfo(ProcessInfo& info) { { // cpuModel from "model" Tokenizer::Token t; - Tokenizer p(keyValuePairs[NS_LITERAL_CSTRING("model")]); + Tokenizer p(keyValuePairs["model"_ns]); if (p.Next(t) && t.Type() == Tokenizer::TOKEN_INTEGER && t.AsInteger() <= INT32_MAX) { cpuModel = static_cast(t.AsInteger()); @@ -734,7 +734,7 @@ nsresult CollectProcessInfo(ProcessInfo& info) { { // cpuStepping from "stepping" Tokenizer::Token t; - Tokenizer p(keyValuePairs[NS_LITERAL_CSTRING("stepping")]); + Tokenizer p(keyValuePairs["stepping"_ns]); if (p.Next(t) && t.Type() == Tokenizer::TOKEN_INTEGER && t.AsInteger() <= INT32_MAX) { cpuStepping = static_cast(t.AsInteger()); @@ -744,7 +744,7 @@ nsresult CollectProcessInfo(ProcessInfo& info) { { // physicalCPUs from "cpu cores" Tokenizer::Token t; - Tokenizer p(keyValuePairs[NS_LITERAL_CSTRING("cpu cores")]); + Tokenizer p(keyValuePairs["cpu cores"_ns]); if (p.Next(t) && t.Type() == Tokenizer::TOKEN_INTEGER && t.AsInteger() <= INT32_MAX) { physicalCPUs = static_cast(t.AsInteger()); @@ -867,11 +867,11 @@ nsresult nsSystemInfo::Init() { NS_ENSURE_SUCCESS(rv, rv); // Additional informations not available through PR_GetSystemInfo. - SetInt32Property(NS_LITERAL_STRING("pagesize"), PR_GetPageSize()); - SetInt32Property(NS_LITERAL_STRING("pageshift"), PR_GetPageShift()); - SetInt32Property(NS_LITERAL_STRING("memmapalign"), PR_GetMemMapAlignment()); - SetUint64Property(NS_LITERAL_STRING("memsize"), PR_GetPhysicalMemorySize()); - SetUint32Property(NS_LITERAL_STRING("umask"), nsSystemInfo::gUserUmask); + SetInt32Property(u"pagesize"_ns, PR_GetPageSize()); + SetInt32Property(u"pageshift"_ns, PR_GetPageShift()); + SetInt32Property(u"memmapalign"_ns, PR_GetMemMapAlignment()); + SetUint64Property(u"memsize"_ns, PR_GetPhysicalMemorySize()); + SetUint32Property(u"umask"_ns, nsSystemInfo::gUserUmask); uint64_t virtualMem = 0; @@ -883,8 +883,7 @@ nsresult nsSystemInfo::Init() { virtualMem = memStat.ullTotalVirtual; } #endif - if (virtualMem) - SetUint64Property(NS_LITERAL_STRING("virtualmemsize"), virtualMem); + if (virtualMem) SetUint64Property(u"virtualmemsize"_ns, virtualMem); for (uint32_t i = 0; i < ArrayLength(cpuPropItems); i++) { rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16(cpuPropItems[i].name), @@ -901,7 +900,7 @@ nsresult nsSystemInfo::Init() { # else false; # endif - rv = SetPropertyAsBool(NS_LITERAL_STRING("isMinGW"), !!isMinGW); + rv = SetPropertyAsBool(u"isMinGW"_ns, !!isMinGW); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -911,24 +910,21 @@ nsresult nsSystemInfo::Init() { if (NS_SUCCEEDED( GetWindowsSecurityCenterInfo(avInfo, antiSpyInfo, firewallInfo))) { if (!avInfo.IsEmpty()) { - rv = SetPropertyAsAString(NS_LITERAL_STRING("registeredAntiVirus"), - avInfo); + rv = SetPropertyAsAString(u"registeredAntiVirus"_ns, avInfo); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } if (!antiSpyInfo.IsEmpty()) { - rv = SetPropertyAsAString(NS_LITERAL_STRING("registeredAntiSpyware"), - antiSpyInfo); + rv = SetPropertyAsAString(u"registeredAntiSpyware"_ns, antiSpyInfo); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } } if (!firewallInfo.IsEmpty()) { - rv = SetPropertyAsAString(NS_LITERAL_STRING("registeredFirewall"), - firewallInfo); + rv = SetPropertyAsAString(u"registeredFirewall"_ns, firewallInfo); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -940,7 +936,7 @@ nsresult nsSystemInfo::Init() { #if defined(XP_MACOSX) nsAutoCString modelId; if (NS_SUCCEEDED(GetAppleModelId(modelId))) { - rv = SetPropertyAsACString(NS_LITERAL_STRING("appleModelId"), modelId); + rv = SetPropertyAsACString(u"appleModelId"_ns, modelId); NS_ENSURE_SUCCESS(rv, rv); } #endif @@ -984,8 +980,7 @@ nsresult nsSystemInfo::Init() { } # endif - rv = SetPropertyAsACString(NS_LITERAL_STRING("secondaryLibrary"), - secondaryLibrary); + rv = SetPropertyAsACString(u"secondaryLibrary"_ns, secondaryLibrary); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1000,23 +995,21 @@ nsresult nsSystemInfo::Init() { #if defined(XP_LINUX) && defined(MOZ_SANDBOX) SandboxInfo sandInfo = SandboxInfo::Get(); - SetPropertyAsBool(NS_LITERAL_STRING("hasSeccompBPF"), + SetPropertyAsBool(u"hasSeccompBPF"_ns, sandInfo.Test(SandboxInfo::kHasSeccompBPF)); - SetPropertyAsBool(NS_LITERAL_STRING("hasSeccompTSync"), + SetPropertyAsBool(u"hasSeccompTSync"_ns, sandInfo.Test(SandboxInfo::kHasSeccompTSync)); - SetPropertyAsBool(NS_LITERAL_STRING("hasUserNamespaces"), + SetPropertyAsBool(u"hasUserNamespaces"_ns, sandInfo.Test(SandboxInfo::kHasUserNamespaces)); - SetPropertyAsBool(NS_LITERAL_STRING("hasPrivilegedUserNamespaces"), + SetPropertyAsBool(u"hasPrivilegedUserNamespaces"_ns, sandInfo.Test(SandboxInfo::kHasPrivilegedUserNamespaces)); if (sandInfo.Test(SandboxInfo::kEnabledForContent)) { - SetPropertyAsBool(NS_LITERAL_STRING("canSandboxContent"), - sandInfo.CanSandboxContent()); + SetPropertyAsBool(u"canSandboxContent"_ns, sandInfo.CanSandboxContent()); } if (sandInfo.Test(SandboxInfo::kEnabledForMedia)) { - SetPropertyAsBool(NS_LITERAL_STRING("canSandboxMedia"), - sandInfo.CanSandboxMedia()); + SetPropertyAsBool(u"canSandboxMedia"_ns, sandInfo.CanSandboxMedia()); } #endif // XP_LINUX && MOZ_SANDBOX @@ -1070,31 +1063,29 @@ void nsSystemInfo::GetAndroidSystemInfo(AndroidSystemInfo* aInfo) { void nsSystemInfo::SetupAndroidInfo(const AndroidSystemInfo& aInfo) { if (!aInfo.device().IsEmpty()) { - SetPropertyAsAString(NS_LITERAL_STRING("device"), aInfo.device()); + SetPropertyAsAString(u"device"_ns, aInfo.device()); } if (!aInfo.manufacturer().IsEmpty()) { - SetPropertyAsAString(NS_LITERAL_STRING("manufacturer"), - aInfo.manufacturer()); + SetPropertyAsAString(u"manufacturer"_ns, aInfo.manufacturer()); } if (!aInfo.release_version().IsEmpty()) { - SetPropertyAsAString(NS_LITERAL_STRING("release_version"), - aInfo.release_version()); + SetPropertyAsAString(u"release_version"_ns, aInfo.release_version()); } - SetPropertyAsBool(NS_LITERAL_STRING("tablet"), aInfo.isTablet()); + SetPropertyAsBool(u"tablet"_ns, aInfo.isTablet()); // NSPR "version" is the kernel version. For Android we want the Android // version. Rename SDK version to version and put the kernel version into // kernel_version. nsAutoString str; - nsresult rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), str); + nsresult rv = GetPropertyAsAString(u"version"_ns, str); if (NS_SUCCEEDED(rv)) { - SetPropertyAsAString(NS_LITERAL_STRING("kernel_version"), str); + SetPropertyAsAString(u"kernel_version"_ns, str); } // When JNI is not available (eg. in xpcshell tests), sdk_version is 0. if (aInfo.sdk_version() != 0) { if (!aInfo.hardware().IsEmpty()) { - SetPropertyAsAString(NS_LITERAL_STRING("hardware"), aInfo.hardware()); + SetPropertyAsAString(u"hardware"_ns, aInfo.hardware()); } - SetPropertyAsInt32(NS_LITERAL_STRING("version"), aInfo.sdk_version()); + SetPropertyAsInt32(u"version"_ns, aInfo.sdk_version()); } } #endif // MOZ_WIDGET_ANDROID diff --git a/xpcom/build/LateWriteChecks.cpp b/xpcom/build/LateWriteChecks.cpp index edf88c79e9d9..de4180a2433d 100644 --- a/xpcom/build/LateWriteChecks.cpp +++ b/xpcom/build/LateWriteChecks.cpp @@ -205,7 +205,7 @@ void LateWriteObserver::Observe( // We append the sha1 of the contents to the file name. This provides a simple // client side deduplication. - nsAutoString finalName(NS_LITERAL_STRING("Telemetry.LateWriteFinal-")); + nsAutoString finalName(u"Telemetry.LateWriteFinal-"_ns); for (int i = 0; i < 20; ++i) { finalName.AppendPrintf("%02x", sha1[i]); } diff --git a/xpcom/build/XPCOMInit.cpp b/xpcom/build/XPCOMInit.cpp index fcfb386a8a15..f64190c9b534 100644 --- a/xpcom/build/XPCOMInit.cpp +++ b/xpcom/build/XPCOMInit.cpp @@ -393,7 +393,7 @@ NS_InitXPCOM(nsIServiceManager** aResult, nsIFile* aBinDirectory, return NS_ERROR_FAILURE; } - rv = binaryFile->AppendNative(NS_LITERAL_CSTRING("nonexistent-executable")); + rv = binaryFile->AppendNative("nonexistent-executable"_ns); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } diff --git a/xpcom/components/ManifestParser.cpp b/xpcom/components/ManifestParser.cpp index 7d7ba6a99d45..d91609f355f8 100644 --- a/xpcom/components/ManifestParser.cpp +++ b/xpcom/components/ManifestParser.cpp @@ -270,8 +270,7 @@ static bool CheckOsFlag(const nsAString& aFlag, const nsAString& aData, bool result = CheckStringFlag(aFlag, aData, aValue, aResult); #if defined(XP_UNIX) && !defined(XP_DARWIN) && !defined(ANDROID) if (result && aResult == eBad) { - result = - CheckStringFlag(aFlag, aData, NS_LITERAL_STRING("likeunix"), aResult); + result = CheckStringFlag(aFlag, aData, u"likeunix"_ns, aResult); } #endif return result; diff --git a/xpcom/components/gen_static_components.py b/xpcom/components/gen_static_components.py index c037f7d9c93c..9ffcd6e1fc0f 100644 --- a/xpcom/components/gen_static_components.py +++ b/xpcom/components/gen_static_components.py @@ -329,7 +329,7 @@ def lower_constructor(self): if self.jsm: res += ( ' nsCOMPtr inst;\n' - ' MOZ_TRY(ConstructJSMComponent(NS_LITERAL_CSTRING(%s),\n' + ' MOZ_TRY(ConstructJSMComponent(nsLiteralCString(%s),\n' ' %s,\n' ' getter_AddRefs(inst)));' '\n' % (json.dumps(self.jsm), json.dumps(self.constructor))) diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp index d613f01a0645..aa4a4e8436fe 100644 --- a/xpcom/components/nsComponentManager.cpp +++ b/xpcom/components/nsComponentManager.cpp @@ -244,8 +244,8 @@ class MOZ_STACK_CLASS EntryWrapper final { nsCString ModuleDescription() { MATCH(nsCString, return entry->mModule ? entry->mModule->Description() - : NS_LITERAL_CSTRING(""), - return NS_LITERAL_CSTRING("")); + : ""_ns, + return ""_ns); } private: @@ -496,8 +496,7 @@ nsresult nsComponentManagerImpl::Init() { if (greOmnijar) { cl->location.Init(greOmnijar, "chrome.manifest"); } else { - nsCOMPtr lf = - CloneAndAppend(greDir, NS_LITERAL_CSTRING("chrome.manifest")); + nsCOMPtr lf = CloneAndAppend(greDir, "chrome.manifest"_ns); cl->location.Init(lf); } @@ -513,8 +512,7 @@ nsresult nsComponentManagerImpl::Init() { if (!equals) { cl = sModuleLocations->AppendElement(); cl->type = NS_APP_LOCATION; - nsCOMPtr lf = - CloneAndAppend(appDir, NS_LITERAL_CSTRING("chrome.manifest")); + nsCOMPtr lf = CloneAndAppend(appDir, "chrome.manifest"_ns); cl->location.Init(lf); } } @@ -1127,10 +1125,8 @@ nsComponentManagerImpl::CreateInstance(const nsCID& aClass, #ifdef SHOW_CI_ON_EXISTING_SERVICE if (entry->ServiceInstance()) { nsAutoCString message; - message = - NS_LITERAL_CSTRING("You are calling CreateInstance \"") + - AutoIDString(aClass) + - NS_LITERAL_CSTRING("\" when a service for this CID already exists!"); + message = "You are calling CreateInstance \""_ns + AutoIDString(aClass) + + "\" when a service for this CID already exists!"_ns; NS_ERROR(message.get()); } #endif @@ -1210,9 +1206,9 @@ nsComponentManagerImpl::CreateInstanceByContractID(const char* aContractID, if (entry->ServiceInstance()) { nsAutoCString message; message = - NS_LITERAL_CSTRING("You are calling CreateInstance \"") + + "You are calling CreateInstance \""_ns + nsDependentCString(aContractID) + - NS_LITERAL_CSTRING( + nsLiteralCString( "\" when a service for this CID already exists! " "Add it to abusedContracts to track down the service consumer."); NS_ERROR(message.get()); @@ -1924,8 +1920,7 @@ nsComponentManagerImpl::AddBootstrappedManifestLocation(nsIFile* aLocation) { return XRE_AddJarManifestLocation(NS_BOOTSTRAPPED_LOCATION, aLocation); } - nsCOMPtr manifest = - CloneAndAppend(aLocation, NS_LITERAL_CSTRING("chrome.manifest")); + nsCOMPtr manifest = CloneAndAppend(aLocation, "chrome.manifest"_ns); return XRE_AddManifestLocation(NS_BOOTSTRAPPED_LOCATION, manifest); } @@ -1950,8 +1945,7 @@ nsComponentManagerImpl::RemoveBootstrappedManifestLocation(nsIFile* aLocation) { if (Substring(path, path.Length() - 4).EqualsLiteral(".xpi")) { elem.location.Init(aLocation, "chrome.manifest"); } else { - nsCOMPtr lf = - CloneAndAppend(aLocation, NS_LITERAL_CSTRING("chrome.manifest")); + nsCOMPtr lf = CloneAndAppend(aLocation, "chrome.manifest"_ns); elem.location.Init(lf); } diff --git a/xpcom/ds/nsAtomTable.cpp b/xpcom/ds/nsAtomTable.cpp index 5936bf79fb74..036d3ce38640 100644 --- a/xpcom/ds/nsAtomTable.cpp +++ b/xpcom/ds/nsAtomTable.cpp @@ -430,9 +430,9 @@ void nsAtomSubTable::GCLocked(GCKind aKind) { if (nonZeroRefcountAtomsCount == 0) { nonZeroRefcountAtoms = name; } else if (nonZeroRefcountAtomsCount < 20) { - nonZeroRefcountAtoms += NS_LITERAL_CSTRING(",") + name; + nonZeroRefcountAtoms += ","_ns + name; } else if (nonZeroRefcountAtomsCount == 20) { - nonZeroRefcountAtoms += NS_LITERAL_CSTRING(",..."); + nonZeroRefcountAtoms += ",..."_ns; } nonZeroRefcountAtomsCount++; } diff --git a/xpcom/ds/nsObserverService.cpp b/xpcom/ds/nsObserverService.cpp index b1cc4d427b5e..19ba295b3a3a 100644 --- a/xpcom/ds/nsObserverService.cpp +++ b/xpcom/ds/nsObserverService.cpp @@ -100,10 +100,10 @@ nsObserverService::CollectReports(nsIHandleReportCallback* aHandleReport, aHandleReport->Callback( /* process */ EmptyCString(), suspectPath, KIND_OTHER, UNITS_COUNT, suspect.mReferentCount, - NS_LITERAL_CSTRING("A topic with a suspiciously large number of " - "referents. This may be symptomatic of a leak " - "if the number of referents is high with " - "respect to the number of windows."), + nsLiteralCString("A topic with a suspiciously large number of " + "referents. This may be symptomatic of a leak " + "if the number of referents is high with " + "respect to the number of windows."), aData); } @@ -190,8 +190,7 @@ nsresult nsObserverService::FilterHttpOnTopics(const char* aTopic) { do_GetService(NS_CONSOLESERVICE_CONTRACTID)); nsCOMPtr error( do_CreateInstance(NS_SCRIPTERROR_CONTRACTID)); - error->Init(NS_LITERAL_STRING( - "http-on-* observers only work in the parent process"), + error->Init(u"http-on-* observers only work in the parent process"_ns, EmptyString(), EmptyString(), 0, 0, nsIScriptError::warningFlag, "chrome javascript", false /* from private window */, true /* from chrome context */); diff --git a/xpcom/io/FilePreferences.cpp b/xpcom/io/FilePreferences.cpp index 5504bc08ca43..f2cf70a44fcb 100644 --- a/xpcom/io/FilePreferences.cpp +++ b/xpcom/io/FilePreferences.cpp @@ -34,7 +34,7 @@ static WinPaths& PathWhitelist() { } #ifdef XP_WIN -const auto kDevicePathSpecifier = NS_LITERAL_STRING("\\\\?\\"); +const auto kDevicePathSpecifier = u"\\\\?\\"_ns; typedef char16_t char_path_t; #else @@ -74,7 +74,7 @@ static void AllowUNCDirectory(char const* directory) { // The whitelist makes sense only for UNC paths, because this code is used // to block only UNC paths, hence, no need to add non-UNC directories here // as those would never pass the check. - if (!StringBeginsWith(path, NS_LITERAL_STRING("\\\\"))) { + if (!StringBeginsWith(path, u"\\\\"_ns)) { return; } @@ -257,7 +257,7 @@ bool IsBlockedUNCPath(const nsAString& aFilePath) { return false; } - if (!StringBeginsWith(aFilePath, NS_LITERAL_STRING("\\\\"))) { + if (!StringBeginsWith(aFilePath, u"\\\\"_ns)) { return false; } diff --git a/xpcom/io/SpecialSystemDirectory.cpp b/xpcom/io/SpecialSystemDirectory.cpp index 66dc123cfbe4..ef4bc5cf0210 100644 --- a/xpcom/io/SpecialSystemDirectory.cpp +++ b/xpcom/io/SpecialSystemDirectory.cpp @@ -377,7 +377,7 @@ static nsresult GetUnixXDGUserDirectory(SystemDirectories aSystemDirectory, return rv; } - rv = file->AppendNative(NS_LITERAL_CSTRING("Desktop")); + rv = file->AppendNative("Desktop"_ns); } else { // no fallback for the other XDG dirs rv = NS_ERROR_FAILURE; diff --git a/xpcom/io/nsAppFileLocationProvider.cpp b/xpcom/io/nsAppFileLocationProvider.cpp index 915e8bc7361e..b8699fecc4b7 100644 --- a/xpcom/io/nsAppFileLocationProvider.cpp +++ b/xpcom/io/nsAppFileLocationProvider.cpp @@ -31,16 +31,16 @@ // come from localizable resources #if defined(MOZ_WIDGET_COCOA) -# define APP_REGISTRY_NAME NS_LITERAL_CSTRING("Application Registry") -# define ESSENTIAL_FILES NS_LITERAL_CSTRING("Essential Files") +# define APP_REGISTRY_NAME "Application Registry"_ns +# define ESSENTIAL_FILES "Essential Files"_ns #elif defined(XP_WIN) -# define APP_REGISTRY_NAME NS_LITERAL_CSTRING("registry.dat") +# define APP_REGISTRY_NAME "registry.dat"_ns #else -# define APP_REGISTRY_NAME NS_LITERAL_CSTRING("appreg") +# define APP_REGISTRY_NAME "appreg"_ns #endif // define default product directory -#define DEFAULT_PRODUCT_DIR NS_LITERAL_CSTRING(MOZ_USER_DIR) +#define DEFAULT_PRODUCT_DIR nsLiteralCString(MOZ_USER_DIR) // Locally defined keys used by nsAppDirectoryEnumerator #define NS_USER_PLUGINS_DIR "UserPlugins" @@ -52,11 +52,11 @@ # define NS_SYSTEM_PLUGINS_DIR "SysPlugins" #endif -#define DEFAULTS_DIR_NAME NS_LITERAL_CSTRING("defaults") -#define DEFAULTS_PREF_DIR_NAME NS_LITERAL_CSTRING("pref") -#define RES_DIR_NAME NS_LITERAL_CSTRING("res") -#define CHROME_DIR_NAME NS_LITERAL_CSTRING("chrome") -#define PLUGINS_DIR_NAME NS_LITERAL_CSTRING("plugins") +#define DEFAULTS_DIR_NAME "defaults"_ns +#define DEFAULTS_PREF_DIR_NAME "pref"_ns +#define RES_DIR_NAME "res"_ns +#define CHROME_DIR_NAME "chrome"_ns +#define PLUGINS_DIR_NAME "plugins"_ns //***************************************************************************** // nsAppFileLocationProvider::Constructor/Destructor @@ -329,7 +329,7 @@ nsresult nsAppFileLocationProvider::GetDefaultUserProfileRoot( #if defined(MOZ_WIDGET_COCOA) || defined(XP_WIN) // These 3 platforms share this part of the path - do them as one - rv = localDir->AppendRelativeNativePath(NS_LITERAL_CSTRING("Profiles")); + rv = localDir->AppendRelativeNativePath("Profiles"_ns); if (NS_FAILED(rv)) { return rv; } diff --git a/xpcom/io/nsLocalFileUnix.cpp b/xpcom/io/nsLocalFileUnix.cpp index 1f03c253b029..5d167e3bf7ae 100644 --- a/xpcom/io/nsLocalFileUnix.cpp +++ b/xpcom/io/nsLocalFileUnix.cpp @@ -656,7 +656,7 @@ nsresult nsLocalFile::GetNativeTargetPathName(nsIFile* aNewParent, return rv; } - aResult = dirName + NS_LITERAL_CSTRING("/") + Substring(nameBegin, nameEnd); + aResult = dirName + "/"_ns + Substring(nameBegin, nameEnd); return NS_OK; } @@ -1965,7 +1965,7 @@ nsLocalFile::Launch() { rv = mimeService->GetTypeFromFile(this, type); } - nsAutoCString fileUri = NS_LITERAL_CSTRING("file://") + mPath; + nsAutoCString fileUri = "file://"_ns + mPath; return java::GeckoAppShell::OpenUriExternal( NS_ConvertUTF8toUTF16(fileUri), NS_ConvertUTF8toUTF16(type), EmptyString(), EmptyString(), EmptyString(), EmptyString()) diff --git a/xpcom/io/nsLocalFileWin.cpp b/xpcom/io/nsLocalFileWin.cpp index bf8c2d79526f..b8ba28381f83 100644 --- a/xpcom/io/nsLocalFileWin.cpp +++ b/xpcom/io/nsLocalFileWin.cpp @@ -1211,7 +1211,7 @@ nsresult nsLocalFile::AppendInternal(const nsString& aNode, } // catches the remaining cases of prefixes - if (StringBeginsWith(aNode, NS_LITERAL_STRING("..\\"))) { + if (StringBeginsWith(aNode, u"..\\"_ns)) { return NS_ERROR_FILE_UNRECOGNIZED_PATH; } } @@ -1304,7 +1304,7 @@ nsLocalFile::Normalize() { if (currentDir.Last() == '\\') { path.Replace(0, 2, currentDir); } else { - path.Replace(0, 2, currentDir + NS_LITERAL_STRING("\\")); + path.Replace(0, 2, currentDir + u"\\"_ns); } } diff --git a/xpcom/string/nsTLiteralString.h b/xpcom/string/nsTLiteralString.h index a3531cafa7cb..7b732652aa49 100644 --- a/xpcom/string/nsTLiteralString.h +++ b/xpcom/string/nsTLiteralString.h @@ -73,7 +73,7 @@ class nsTLiteralString : public mozilla::detail::nsTStringRepr { #endif /** - * Prohibit get() on temporaries as in nsLiteralCString("x").get(). + * Prohibit get() on temporaries as in "x"_ns.get(). * These should be written as just "x", using a string literal directly. */ const typename raw_type::type get() const&& = delete; diff --git a/xpcom/tests/TestHarness.h b/xpcom/tests/TestHarness.h index 84264d32ad0a..c0f5afe22eab 100644 --- a/xpcom/tests/TestHarness.h +++ b/xpcom/tests/TestHarness.h @@ -143,7 +143,7 @@ class ScopedXPCOM : public nsIDirectoryServiceProvider2 { getter_AddRefs(profD)); NS_ENSURE_SUCCESS(rv, nullptr); - rv = profD->Append(NS_LITERAL_STRING("cpp-unit-profd")); + rv = profD->Append(u"cpp-unit-profd"_ns); NS_ENSURE_SUCCESS(rv, nullptr); rv = profD->CreateUnique(nsIFile::DIRECTORY_TYPE, 0755); @@ -185,7 +185,7 @@ class ScopedXPCOM : public nsIDirectoryServiceProvider2 { nsAutoCString leafName; mGREBinD->GetNativeLeafName(leafName); if (leafName.EqualsLiteral("Resources")) { - mGREBinD->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS")); + mGREBinD->SetNativeLeafName("MacOS"_ns); } #endif diff --git a/xpcom/tests/gtest/TestAtoms.cpp b/xpcom/tests/gtest/TestAtoms.cpp index e712bca2dd33..53ec5a0e6e9e 100644 --- a/xpcom/tests/gtest/TestAtoms.cpp +++ b/xpcom/tests/gtest/TestAtoms.cpp @@ -55,7 +55,7 @@ TEST(Atoms, 16vs8) TEST(Atoms, Null) { - nsAutoString str(NS_LITERAL_STRING("string with a \0 char")); + nsAutoString str(u"string with a \0 char"_ns); nsDependentString strCut(str.get()); EXPECT_FALSE(str.Equals(strCut)); diff --git a/xpcom/tests/gtest/TestDafsa.cpp b/xpcom/tests/gtest/TestDafsa.cpp index 523c74629020..f52bf7425624 100644 --- a/xpcom/tests/gtest/TestDafsa.cpp +++ b/xpcom/tests/gtest/TestDafsa.cpp @@ -22,16 +22,16 @@ TEST(Dafsa, StringsFound) { Dafsa d(dafsa_test_1::kDafsa); - int tag = d.Lookup(NS_LITERAL_CSTRING("foo.bar.baz")); + int tag = d.Lookup("foo.bar.baz"_ns); EXPECT_EQ(tag, 1); - tag = d.Lookup(NS_LITERAL_CSTRING("a.test.string")); + tag = d.Lookup("a.test.string"_ns); EXPECT_EQ(tag, 0); - tag = d.Lookup(NS_LITERAL_CSTRING("a.test.string2")); + tag = d.Lookup("a.test.string2"_ns); EXPECT_EQ(tag, 2); - tag = d.Lookup(NS_LITERAL_CSTRING("aaaa")); + tag = d.Lookup("aaaa"_ns); EXPECT_EQ(tag, 4); } @@ -40,23 +40,23 @@ TEST(Dafsa, StringsNotFound) Dafsa d(dafsa_test_1::kDafsa); // Matches all but last letter. - int tag = d.Lookup(NS_LITERAL_CSTRING("foo.bar.ba")); + int tag = d.Lookup("foo.bar.ba"_ns); EXPECT_EQ(tag, Dafsa::kKeyNotFound); // Matches prefix with extra letter. - tag = d.Lookup(NS_LITERAL_CSTRING("a.test.strings")); + tag = d.Lookup("a.test.strings"_ns); EXPECT_EQ(tag, Dafsa::kKeyNotFound); // Matches small portion. - tag = d.Lookup(NS_LITERAL_CSTRING("a.test")); + tag = d.Lookup("a.test"_ns); EXPECT_EQ(tag, Dafsa::kKeyNotFound); // Matches repeating pattern with extra letters. - tag = d.Lookup(NS_LITERAL_CSTRING("aaaaa")); + tag = d.Lookup("aaaaa"_ns); EXPECT_EQ(tag, Dafsa::kKeyNotFound); // Empty string. - tag = d.Lookup(NS_LITERAL_CSTRING("")); + tag = d.Lookup(""_ns); EXPECT_EQ(tag, Dafsa::kKeyNotFound); } @@ -64,7 +64,7 @@ TEST(Dafsa, HugeString) { Dafsa d(dafsa_test_1::kDafsa); - int tag = d.Lookup(NS_LITERAL_CSTRING( + int tag = d.Lookup(nsLiteralCString( "This is a very long string that is larger than the dafsa itself. " "This is a very long string that is larger than the dafsa itself. " "This is a very long string that is larger than the dafsa itself. " diff --git a/xpcom/tests/gtest/TestEventTargetQI.cpp b/xpcom/tests/gtest/TestEventTargetQI.cpp index 96ea9829e606..bc6378fe34ff 100644 --- a/xpcom/tests/gtest/TestEventTargetQI.cpp +++ b/xpcom/tests/gtest/TestEventTargetQI.cpp @@ -39,8 +39,7 @@ TEST(TestEventTargetQI, ThreadPool) TEST(TestEventTargetQI, SharedThreadPool) { - nsCOMPtr thing = - SharedThreadPool::Get(NS_LITERAL_CSTRING("TestPool"), 1); + nsCOMPtr thing = SharedThreadPool::Get("TestPool"_ns, 1); EXPECT_TRUE(thing); EXPECT_FALSE(TestQITo(thing)); @@ -72,8 +71,7 @@ TEST(TestEventTargetQI, ThrottledEventQueue) TEST(TestEventTargetQI, LazyIdleThread) { - nsCOMPtr thing = - new LazyIdleThread(0, NS_LITERAL_CSTRING("TestThread")); + nsCOMPtr thing = new LazyIdleThread(0, "TestThread"_ns); EXPECT_TRUE(thing); EXPECT_TRUE(TestQITo(thing)); diff --git a/xpcom/tests/gtest/TestFile.cpp b/xpcom/tests/gtest/TestFile.cpp index e5e19f92eb82..38c93fedd247 100644 --- a/xpcom/tests/gtest/TestFile.cpp +++ b/xpcom/tests/gtest/TestFile.cpp @@ -495,7 +495,7 @@ TEST(TestFile, Unprefixed) gTestWithPrefix_Win = false; #endif - SetupAndTestFunctions(NS_LITERAL_STRING("mozfiletests"), + SetupAndTestFunctions(u"mozfiletests"_ns, /* aTestCreateUnique */ true, /* aTestNormalize */ true); @@ -508,7 +508,7 @@ TEST(TestFile, Unprefixed) // SetUseDOSDevicePathSyntax if it's on Windows for NewFile) TEST(TestFile, PrefixedOnWin) { - SetupAndTestFunctions(NS_LITERAL_STRING("mozfiletests"), + SetupAndTestFunctions(u"mozfiletests"_ns, /* aTestCreateUnique */ true, /* aTestNormalize */ true); } @@ -536,7 +536,7 @@ TEST(TestFile, PrefixedOnWin_ComponentEndsWithPeriod) { // Bypass the normalization for this because it would strip the trailing // period. - SetupAndTestFunctions(NS_LITERAL_STRING("mozfiletests."), + SetupAndTestFunctions(u"mozfiletests."_ns, /* aTestCreateUnique */ true, /* aTestNormalize */ false); } diff --git a/xpcom/tests/gtest/TestFilePreferencesUnix.cpp b/xpcom/tests/gtest/TestFilePreferencesUnix.cpp index 2e0348e59710..b48f7d0a72e8 100644 --- a/xpcom/tests/gtest/TestFilePreferencesUnix.cpp +++ b/xpcom/tests/gtest/TestFilePreferencesUnix.cpp @@ -28,15 +28,13 @@ TEST(TestFilePreferencesUnix, Parsing) nsresult rv = Preferences::ClearUser(kForbiddenPathsPref); ASSERT_EQ(rv, NS_OK); FilePreferences::InitPrefs(); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbidden)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbidden)), true); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbiddenDir)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbiddenDir)), true); - ASSERT_EQ( - FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbiddenFile)), - true); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kAllowed)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbiddenFile)), true); + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kAllowed)), true); }); auto CheckPrefs = [](const nsACString& aPaths) { @@ -44,25 +42,23 @@ TEST(TestFilePreferencesUnix, Parsing) rv = Preferences::SetCString(kForbiddenPathsPref, aPaths); ASSERT_EQ(rv, NS_OK); FilePreferences::InitPrefs(); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbiddenDir)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbiddenDir)), false); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbiddenDir)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbiddenDir)), false); - ASSERT_EQ( - FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbiddenFile)), - false); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kForbidden)), + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbiddenFile)), false); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kAllowed)), - true); + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kForbidden)), + false); + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kAllowed)), true); }; - CheckPrefs(NS_LITERAL_CSTRING(kForbidden)); - CheckPrefs(NS_LITERAL_CSTRING(kForbidden "," kOther)); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kOtherFile)), + CheckPrefs(nsLiteralCString(kForbidden)); + CheckPrefs(nsLiteralCString(kForbidden "," kOther)); + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kOtherFile)), false); - CheckPrefs(NS_LITERAL_CSTRING(kForbidden "," kOther ",")); - ASSERT_EQ(FilePreferences::IsAllowedPath(NS_LITERAL_CSTRING(kOtherFile)), + CheckPrefs(nsLiteralCString(kForbidden "," kOther ",")); + ASSERT_EQ(FilePreferences::IsAllowedPath(nsLiteralCString(kOtherFile)), false); } @@ -77,7 +73,7 @@ TEST(TestFilePreferencesUnix, Simple) ASSERT_EQ(rv, NS_OK); rv = forbiddenDir->GetNativePath(tempPath); ASSERT_EQ(rv, NS_OK); - rv = forbiddenDir->AppendNative(NS_LITERAL_CSTRING("forbidden_dir")); + rv = forbiddenDir->AppendNative("forbidden_dir"_ns); ASSERT_EQ(rv, NS_OK); // This is executed at exit to clean up after ourselves. @@ -98,7 +94,7 @@ TEST(TestFilePreferencesUnix, Simple) nsCOMPtr forbiddenFile; rv = forbiddenDir->Clone(getter_AddRefs(forbiddenFile)); ASSERT_EQ(rv, NS_OK); - rv = forbiddenFile->AppendNative(NS_LITERAL_CSTRING("test_file")); + rv = forbiddenFile->AppendNative("test_file"_ns); // Create the file ASSERT_EQ(rv, NS_OK); @@ -131,14 +127,14 @@ TEST(TestFilePreferencesUnix, Simple) nsCOMPtr newPath; rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(newPath)); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendNative(NS_LITERAL_CSTRING(".")); + rv = newPath->AppendNative("."_ns); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendNative(NS_LITERAL_CSTRING("forbidden_dir")); + rv = newPath->AppendNative("forbidden_dir"_ns); ASSERT_EQ(rv, NS_OK); rv = newPath->Exists(&exists); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); - rv = newPath->AppendNative(NS_LITERAL_CSTRING("test_file")); + rv = newPath->AppendNative("test_file"_ns); ASSERT_EQ(rv, NS_OK); rv = newPath->Exists(&exists); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); @@ -146,8 +142,7 @@ TEST(TestFilePreferencesUnix, Simple) // Check that ./ does not bypass the filter rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(newPath)); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendRelativeNativePath( - NS_LITERAL_CSTRING("./forbidden_dir/file")); + rv = newPath->AppendRelativeNativePath("./forbidden_dir/file"_ns); ASSERT_EQ(rv, NS_OK); rv = newPath->Exists(&exists); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); @@ -155,19 +150,18 @@ TEST(TestFilePreferencesUnix, Simple) // Check that .. does not bypass the filter rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(newPath)); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendRelativeNativePath( - NS_LITERAL_CSTRING("allowed/../forbidden_dir/file")); + rv = newPath->AppendRelativeNativePath("allowed/../forbidden_dir/file"_ns); ASSERT_EQ(rv, NS_OK); rv = newPath->Exists(&exists); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(newPath)); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendNative(NS_LITERAL_CSTRING("allowed")); + rv = newPath->AppendNative("allowed"_ns); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendNative(NS_LITERAL_CSTRING("..")); + rv = newPath->AppendNative(".."_ns); ASSERT_EQ(rv, NS_OK); - rv = newPath->AppendNative(NS_LITERAL_CSTRING("forbidden_dir")); + rv = newPath->AppendNative("forbidden_dir"_ns); ASSERT_EQ(rv, NS_OK); rv = newPath->Exists(&exists); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); diff --git a/xpcom/tests/gtest/TestFilePreferencesWin.cpp b/xpcom/tests/gtest/TestFilePreferencesWin.cpp index 16ad5a037bec..fdf777c6f442 100644 --- a/xpcom/tests/gtest/TestFilePreferencesWin.cpp +++ b/xpcom/tests/gtest/TestFilePreferencesWin.cpp @@ -8,110 +8,103 @@ TEST(FilePreferencesWin, Normalization) { nsAutoString normalized; - mozilla::FilePreferences::testing::NormalizePath(NS_LITERAL_STRING("foo"), - normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("foo")); + mozilla::FilePreferences::testing::NormalizePath(u"foo"_ns, normalized); + ASSERT_TRUE(normalized == u"foo"_ns); - mozilla::FilePreferences::testing::NormalizePath(NS_LITERAL_STRING("\\foo"), - normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\foo")); + mozilla::FilePreferences::testing::NormalizePath(u"\\foo"_ns, normalized); + ASSERT_TRUE(normalized == u"\\foo"_ns); - mozilla::FilePreferences::testing::NormalizePath(NS_LITERAL_STRING("\\\\foo"), - normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo"_ns, normalized); + ASSERT_TRUE(normalized == u"\\\\foo"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("foo\\some"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("foo\\some")); + mozilla::FilePreferences::testing::NormalizePath(u"foo\\some"_ns, normalized); + ASSERT_TRUE(normalized == u"foo\\some"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\.\\foo"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo")); - - mozilla::FilePreferences::testing::NormalizePath(NS_LITERAL_STRING("\\\\."), + mozilla::FilePreferences::testing::NormalizePath(u"\\\\.\\foo"_ns, normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + ASSERT_TRUE(normalized == u"\\\\foo"_ns); - mozilla::FilePreferences::testing::NormalizePath(NS_LITERAL_STRING("\\\\.\\"), - normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\."_ns, normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\.\\."), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\.\\"_ns, normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\bar")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\.\\."_ns, normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\bar\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\bar"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\."), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\bar\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\bar\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\.\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\bar\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\."_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\bar\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\..\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\.\\"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\bar\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\.."), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\foo\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\..\\"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\..\\bar\\..\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\.."_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\foo\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\..\\bar"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\bar")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\..\\bar\\..\\"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); - mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\..\\..\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\..\\bar"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\bar"_ns); + + mozilla::FilePreferences::testing::NormalizePath(u"\\\\foo\\bar\\..\\..\\"_ns, + normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\.\\..\\.\\..\\"), normalized); - ASSERT_TRUE(normalized == NS_LITERAL_STRING("\\\\")); + u"\\\\foo\\bar\\.\\..\\.\\..\\"_ns, normalized); + ASSERT_TRUE(normalized == u"\\\\"_ns); bool result; - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\.."), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\.."_ns, + normalized); ASSERT_FALSE(result); - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\..\\"), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\..\\"_ns, + normalized); ASSERT_FALSE(result); - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\.\\..\\"), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\.\\..\\"_ns, + normalized); ASSERT_FALSE(result); result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\\\bar"), normalized); + u"\\\\foo\\\\bar"_ns, normalized); ASSERT_FALSE(result); result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\foo\\bar\\..\\..\\..\\..\\"), normalized); + u"\\\\foo\\bar\\..\\..\\..\\..\\"_ns, normalized); ASSERT_FALSE(result); - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\\\"), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\\\"_ns, + normalized); ASSERT_FALSE(result); - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\.\\\\"), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\.\\\\"_ns, + normalized); ASSERT_FALSE(result); - result = mozilla::FilePreferences::testing::NormalizePath( - NS_LITERAL_STRING("\\\\..\\\\"), normalized); + result = mozilla::FilePreferences::testing::NormalizePath(u"\\\\..\\\\"_ns, + normalized); ASSERT_FALSE(result); } @@ -123,27 +116,26 @@ TEST(FilePreferencesWin, AccessUNC) mozilla::FilePreferences::testing::SetBlockUNCPaths(false); - rv = lf->InitWithPath(NS_LITERAL_STRING("\\\\nice\\..\\evil\\share")); + rv = lf->InitWithPath(u"\\\\nice\\..\\evil\\share"_ns); ASSERT_EQ(rv, NS_OK); mozilla::FilePreferences::testing::SetBlockUNCPaths(true); - rv = lf->InitWithPath(NS_LITERAL_STRING("\\\\nice\\..\\evil\\share")); + rv = lf->InitWithPath(u"\\\\nice\\..\\evil\\share"_ns); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); - mozilla::FilePreferences::testing::AddDirectoryToWhitelist( - NS_LITERAL_STRING("\\\\nice")); + mozilla::FilePreferences::testing::AddDirectoryToWhitelist(u"\\\\nice"_ns); - rv = lf->InitWithPath(NS_LITERAL_STRING("\\\\nice\\share")); + rv = lf->InitWithPath(u"\\\\nice\\share"_ns); ASSERT_EQ(rv, NS_OK); - rv = lf->InitWithPath(NS_LITERAL_STRING("\\\\nice\\..\\evil\\share")); + rv = lf->InitWithPath(u"\\\\nice\\..\\evil\\share"_ns); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); } TEST(FilePreferencesWin, AccessDOSDevicePath) { - const auto devicePathSpecifier = NS_LITERAL_STRING("\\\\?\\"); + const auto devicePathSpecifier = u"\\\\?\\"_ns; nsCOMPtr lf = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID); @@ -151,15 +143,13 @@ TEST(FilePreferencesWin, AccessDOSDevicePath) mozilla::FilePreferences::testing::SetBlockUNCPaths(true); - rv = lf->InitWithPath(devicePathSpecifier + - NS_LITERAL_STRING("evil\\z:\\share")); + rv = lf->InitWithPath(devicePathSpecifier + u"evil\\z:\\share"_ns); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); - rv = lf->InitWithPath(devicePathSpecifier + - NS_LITERAL_STRING("UNC\\evil\\share")); + rv = lf->InitWithPath(devicePathSpecifier + u"UNC\\evil\\share"_ns); ASSERT_EQ(rv, NS_ERROR_FILE_ACCESS_DENIED); - rv = lf->InitWithPath(devicePathSpecifier + NS_LITERAL_STRING("C:\\")); + rv = lf->InitWithPath(devicePathSpecifier + u"C:\\"_ns); ASSERT_EQ(rv, NS_OK); nsCOMPtr base; @@ -179,26 +169,26 @@ TEST(FilePreferencesWin, StartsWithDiskDesignatorAndBackslash) bool result; result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("\\\\UNC\\path")); + u"\\\\UNC\\path"_ns); ASSERT_FALSE(result); result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("\\single\\backslash")); + u"\\single\\backslash"_ns); ASSERT_FALSE(result); result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("C:relative")); + u"C:relative"_ns); ASSERT_FALSE(result); result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("\\\\?\\C:\\")); + u"\\\\?\\C:\\"_ns); ASSERT_FALSE(result); result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("C:\\")); + u"C:\\"_ns); ASSERT_TRUE(result); result = mozilla::FilePreferences::StartsWithDiskDesignatorAndBackslash( - NS_LITERAL_STRING("c:\\")); + u"c:\\"_ns); ASSERT_TRUE(result); } diff --git a/xpcom/tests/gtest/TestHashtables.cpp b/xpcom/tests/gtest/TestHashtables.cpp index 0d30343d825b..dce2cc42daef 100644 --- a/xpcom/tests/gtest/TestHashtables.cpp +++ b/xpcom/tests/gtest/TestHashtables.cpp @@ -438,7 +438,7 @@ TEST(Hashtables, ClassHashtable) ASSERT_TRUE(EntToUniClass.Get(nsDependentCString(entity.mStr), &myChar)); } - ASSERT_FALSE(EntToUniClass.Get(NS_LITERAL_CSTRING("xxxx"), &myChar)); + ASSERT_FALSE(EntToUniClass.Get("xxxx"_ns, &myChar)); uint32_t count = 0; for (auto iter = EntToUniClass.Iter(); !iter.Done(); iter.Next()) { @@ -728,7 +728,7 @@ TEST(Hashtables, ClassHashtable_LookupOrAdd_Present) mozilla::MakeUnique(entity.mUnicode)); } - auto* entry = EntToUniClass.LookupOrAdd(NS_LITERAL_CSTRING("uml"), 42); + auto* entry = EntToUniClass.LookupOrAdd("uml"_ns, 42); EXPECT_EQ(168u, entry->GetChar()); } @@ -737,7 +737,7 @@ TEST(Hashtables, ClassHashtable_LookupOrAdd_NotPresent) nsClassHashtable EntToUniClass(ENTITY_COUNT); // This is going to insert a TestUniChar. - auto* entry = EntToUniClass.LookupOrAdd(NS_LITERAL_CSTRING("uml"), 42); + auto* entry = EntToUniClass.LookupOrAdd("uml"_ns, 42); EXPECT_EQ(42u, entry->GetChar()); } @@ -751,8 +751,7 @@ TEST(Hashtables, ClassHashtable_LookupOrAddFromFactory_Present) } auto* entry = EntToUniClass.LookupOrAddFromFactory( - NS_LITERAL_CSTRING("uml"), - [] { return mozilla::MakeUnique(42); }); + "uml"_ns, [] { return mozilla::MakeUnique(42); }); EXPECT_EQ(168u, entry->GetChar()); } @@ -762,8 +761,7 @@ TEST(Hashtables, ClassHashtable_LookupOrAddFromFactory_NotPresent) // This is going to insert a TestUniCharDerived. auto* entry = EntToUniClass.LookupOrAddFromFactory( - NS_LITERAL_CSTRING("uml"), - [] { return mozilla::MakeUnique(42); }); + "uml"_ns, [] { return mozilla::MakeUnique(42); }); EXPECT_EQ(42u, entry->GetChar()); } @@ -785,7 +783,7 @@ TEST(Hashtables, RefPtrHashtable) ASSERT_TRUE(EntToUniClass.Get(nsDependentCString(entity.mStr), &myChar)); } - ASSERT_FALSE(EntToUniClass.Get(NS_LITERAL_CSTRING("xxxx"), &myChar)); + ASSERT_FALSE(EntToUniClass.Get("xxxx"_ns, &myChar)); uint32_t count = 0; for (auto iter = EntToUniClass.Iter(); !iter.Done(); iter.Next()) { diff --git a/xpcom/tests/gtest/TestLogCommandLineHandler.cpp b/xpcom/tests/gtest/TestLogCommandLineHandler.cpp index dad8e917aadc..b98c286e1339 100644 --- a/xpcom/tests/gtest/TestLogCommandLineHandler.cpp +++ b/xpcom/tests/gtest/TestLogCommandLineHandler.cpp @@ -48,26 +48,26 @@ TEST(LogCommandLineHandler, MOZ_LOG_regular) results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv1), argv1, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=module1:5,module2:4,sync,timestamp") - .Equals(results[0])); + EXPECT_TRUE( + "MOZ_LOG=module1:5,module2:4,sync,timestamp"_ns.Equals(results[0])); char const* argv2[] = {"", "-MOZ_LOG=modules"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv2), argv2, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); char const* argv3[] = {"", "--MOZ_LOG", "modules"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv3), argv3, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); char const* argv4[] = {"", "--MOZ_LOG=modules"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv4), argv4, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); } TEST(LogCommandLineHandler, MOZ_LOG_and_FILE_regular) @@ -83,38 +83,37 @@ TEST(LogCommandLineHandler, MOZ_LOG_and_FILE_regular) results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv1), argv1, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); - EXPECT_TRUE( - NS_LITERAL_CSTRING("MOZ_LOG_FILE=c:\\file/path").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG_FILE=c:\\file/path"_ns.Equals(results[1])); char const* argv2[] = {"", "-MOZ_LOG=modules", "-MOZ_LOG_FILE=file"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv2), argv2, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG_FILE=file").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG_FILE=file"_ns.Equals(results[1])); char const* argv3[] = {"", "--MOZ_LOG", "modules", "--MOZ_LOG_FILE", "file"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv3), argv3, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG_FILE=file").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG_FILE=file"_ns.Equals(results[1])); char const* argv4[] = {"", "--MOZ_LOG=modules", "--MOZ_LOG_FILE=file"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv4), argv4, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG_FILE=file").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG_FILE=file"_ns.Equals(results[1])); char const* argv5[] = {"", "--MOZ_LOG", "modules", "-P", "foo", "--MOZ_LOG_FILE", "file"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv5), argv5, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG_FILE=file").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG_FILE=file"_ns.Equals(results[1])); } TEST(LogCommandLineHandler, MOZ_LOG_fuzzy) @@ -163,20 +162,20 @@ TEST(LogCommandLineHandler, MOZ_LOG_overlapping) results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv1), argv1, callback); EXPECT_TRUE(results.Length() == 2); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules1").Equals(results[0])); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules2").Equals(results[1])); + EXPECT_TRUE("MOZ_LOG=modules1"_ns.Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules2"_ns.Equals(results[1])); char const* argv2[] = {"", "-MOZ_LOG", "--MOZ_LOG", "modules"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv2), argv2, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); char const* argv3[] = {"", "-MOZ_LOG_FILE", "-MOZ_LOG", "modules"}; results.Clear(); mozilla::LoggingHandleCommandLineArgs(array_size(argv3), argv3, callback); EXPECT_TRUE(results.Length() == 1); - EXPECT_TRUE(NS_LITERAL_CSTRING("MOZ_LOG=modules").Equals(results[0])); + EXPECT_TRUE("MOZ_LOG=modules"_ns.Equals(results[0])); char const* argv4[] = {"", "-MOZ_LOG", "-MOZ_LOG_FILE", "-MOZ_LOG"}; results.Clear(); diff --git a/xpcom/tests/gtest/TestMruCache.cpp b/xpcom/tests/gtest/TestMruCache.cpp index 5129c7983654..8cf97408d1d8 100644 --- a/xpcom/tests/gtest/TestMruCache.cpp +++ b/xpcom/tests/gtest/TestMruCache.cpp @@ -239,7 +239,7 @@ TEST(MruCache, TestRemove) // Fill it up. for (char i = 1; i < 32; i++) { const nsCString key = MakeStringKey(i); - mru.Put(key, StringStruct{key, NS_LITERAL_CSTRING("foo")}); + mru.Put(key, StringStruct{key, "foo"_ns}); } // Now remove each value. @@ -384,12 +384,12 @@ TEST(MruCache, TestLookupAndSetWithMove) StringStructMap mru; const nsCString key = MakeStringKey((char)1); - StringStruct val{key, NS_LITERAL_CSTRING("foo")}; + StringStruct val{key, "foo"_ns}; auto p = mru.Lookup(key); EXPECT_FALSE(p); p.Set(std::move(val)); EXPECT_TRUE(p.Data().mKey == key); - EXPECT_TRUE(p.Data().mOther == NS_LITERAL_CSTRING("foo")); + EXPECT_TRUE(p.Data().mOther == "foo"_ns); } diff --git a/xpcom/tests/gtest/TestObserverService.cpp b/xpcom/tests/gtest/TestObserverService.cpp index e4116f48c959..9ff2332b24d0 100644 --- a/xpcom/tests/gtest/TestObserverService.cpp +++ b/xpcom/tests/gtest/TestObserverService.cpp @@ -108,12 +108,12 @@ TEST(ObserverService, AddObserver) do_CreateInstance("@mozilla.org/observer-service;1"); // Add a strong ref. - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); nsresult rv = svc->AddObserver(a, "Foo", false); testResult(rv); // Add a few weak ref. - RefPtr b = new TestObserver(NS_LITERAL_STRING("B")); + RefPtr b = new TestObserver(u"B"_ns); rv = svc->AddObserver(b, "Bar", true); testResult(rv); } @@ -123,9 +123,9 @@ TEST(ObserverService, RemoveObserver) nsCOMPtr svc = do_CreateInstance("@mozilla.org/observer-service;1"); - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); - RefPtr b = new TestObserver(NS_LITERAL_STRING("B")); - RefPtr c = new TestObserver(NS_LITERAL_STRING("C")); + RefPtr a = new TestObserver(u"A"_ns); + RefPtr b = new TestObserver(u"B"_ns); + RefPtr c = new TestObserver(u"C"_ns); svc->AddObserver(a, "Foo", false); svc->AddObserver(b, "Foo", true); @@ -154,7 +154,7 @@ TEST(ObserverService, EnumerateEmpty) TestExpectedCount(svc, "A", 0); // Now add an observer and enumerate an unobserved topic. - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); testResult(svc->AddObserver(a, "Foo", false)); TestExpectedCount(svc, "A", 0); @@ -167,13 +167,13 @@ TEST(ObserverService, Enumerate) const size_t kFooCount = 10; for (size_t i = 0; i < kFooCount; i++) { - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); testResult(svc->AddObserver(a, "Foo", false)); } const size_t kBarCount = kFooCount / 2; for (size_t i = 0; i < kBarCount; i++) { - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); testResult(svc->AddObserver(a, "Bar", false)); } @@ -191,7 +191,7 @@ TEST(ObserverService, EnumerateWeakRefs) const size_t kFooCount = 10; for (size_t i = 0; i < kFooCount; i++) { - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); testResult(svc->AddObserver(a, "Foo", true)); } @@ -200,8 +200,8 @@ TEST(ObserverService, EnumerateWeakRefs) // Now test a mixture. for (size_t i = 0; i < kFooCount; i++) { - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); - RefPtr b = new TestObserver(NS_LITERAL_STRING("B")); + RefPtr a = new TestObserver(u"A"_ns); + RefPtr b = new TestObserver(u"B"_ns); // Register a as weak for "Foo". testResult(svc->AddObserver(a, "Foo", true)); @@ -214,9 +214,9 @@ TEST(ObserverService, EnumerateWeakRefs) TestExpectedCount(svc, "Foo", kFooCount); // Now add a couple weak refs, but don't go out of scope. - RefPtr a = new TestObserver(NS_LITERAL_STRING("A")); + RefPtr a = new TestObserver(u"A"_ns); testResult(svc->AddObserver(a, "Foo", true)); - RefPtr b = new TestObserver(NS_LITERAL_STRING("B")); + RefPtr b = new TestObserver(u"B"_ns); testResult(svc->AddObserver(b, "Foo", true)); // Expect all the observers from before and the two new ones. @@ -233,10 +233,8 @@ TEST(ObserverService, TestNotify) nsCOMPtr svc = do_CreateInstance("@mozilla.org/observer-service;1"); - RefPtr aObserver = - new TestObserver(NS_LITERAL_STRING("Observer-A")); - RefPtr bObserver = - new TestObserver(NS_LITERAL_STRING("Observer-B")); + RefPtr aObserver = new TestObserver(u"Observer-A"_ns); + RefPtr bObserver = new TestObserver(u"Observer-B"_ns); // Add two observers for topicA. testResult(svc->AddObserver(aObserver, topicA.get(), false)); diff --git a/xpcom/tests/gtest/TestStrings.cpp b/xpcom/tests/gtest/TestStrings.cpp index 8a7eca8ea84e..513643eb9b5e 100644 --- a/xpcom/tests/gtest/TestStrings.cpp +++ b/xpcom/tests/gtest/TestStrings.cpp @@ -570,7 +570,7 @@ TEST_F(Strings, DependentStrings) { TEST_F(Strings, assign) { nsCString result; - test_assign_helper(NS_LITERAL_CSTRING("a") + NS_LITERAL_CSTRING("b"), result); + test_assign_helper("a"_ns + "b"_ns, result); EXPECT_STREQ(result.get(), "ab"); } @@ -665,7 +665,7 @@ TEST_F(Strings, findinreadable) { nsACString::const_iterator delim_begin(begin), delim_end(end); // Search for last !/ at the end of the string - EXPECT_TRUE(FindInReadable(NS_LITERAL_CSTRING("!/"), delim_begin, delim_end)); + EXPECT_TRUE(FindInReadable("!/"_ns, delim_begin, delim_end)); char* r = ToNewCString(Substring(delim_begin, delim_end)); // Should match the first "!/" but not the last EXPECT_NE(delim_end, end); @@ -676,8 +676,7 @@ TEST_F(Strings, findinreadable) { delim_end = end; // Search for first jar: - EXPECT_TRUE( - FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_TRUE(FindInReadable("jar:"_ns, delim_begin, delim_end)); r = ToNewCString(Substring(delim_begin, delim_end)); // Should not match the first jar:, but the second one @@ -689,8 +688,7 @@ TEST_F(Strings, findinreadable) { delim_begin = begin; delim_begin++; delim_end = end; - EXPECT_TRUE( - FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_TRUE(FindInReadable("jar:"_ns, delim_begin, delim_end)); r = ToNewCString(Substring(delim_begin, delim_end)); // Should not match the first jar:, but the second one @@ -699,8 +697,7 @@ TEST_F(Strings, findinreadable) { free(r); // Should not find a match - EXPECT_FALSE( - FindInReadable(NS_LITERAL_CSTRING("gecko"), delim_begin, delim_end)); + EXPECT_FALSE(FindInReadable("gecko"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -709,8 +706,7 @@ TEST_F(Strings, findinreadable) { delim_begin = begin; for (int i = 0; i < 6; i++) delim_begin++; delim_end = end; - EXPECT_FALSE( - FindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_FALSE(FindInReadable("jar:"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -719,8 +715,7 @@ TEST_F(Strings, findinreadable) { delim_begin = begin; delim_end = end; for (int i = 0; i < 7; i++) delim_end--; - EXPECT_FALSE( - FindInReadable(NS_LITERAL_CSTRING("classic"), delim_begin, delim_end)); + EXPECT_FALSE(FindInReadable("classic"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -738,8 +733,7 @@ TEST_F(Strings, rfindinreadable) { nsACString::const_iterator delim_begin(begin), delim_end(end); // Search for last !/ at the end of the string - EXPECT_TRUE( - RFindInReadable(NS_LITERAL_CSTRING("!/"), delim_begin, delim_end)); + EXPECT_TRUE(RFindInReadable("!/"_ns, delim_begin, delim_end)); char* r = ToNewCString(Substring(delim_begin, delim_end)); // Should match the last "!/" EXPECT_EQ(delim_end, end); @@ -750,8 +744,7 @@ TEST_F(Strings, rfindinreadable) { delim_end = end; // Search for last jar: but not the first one... - EXPECT_TRUE( - RFindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_TRUE(RFindInReadable("jar:"_ns, delim_begin, delim_end)); r = ToNewCString(Substring(delim_begin, delim_end)); // Should not match the first jar:, but the second one @@ -763,8 +756,7 @@ TEST_F(Strings, rfindinreadable) { delim_begin = begin; delim_end = begin; for (int i = 0; i < 6; i++) delim_end++; - EXPECT_TRUE( - RFindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_TRUE(RFindInReadable("jar:"_ns, delim_begin, delim_end)); r = ToNewCString(Substring(delim_begin, delim_end)); // Should not match the first jar:, but the second one @@ -775,8 +767,7 @@ TEST_F(Strings, rfindinreadable) { // Should not find a match delim_begin = begin; delim_end = end; - EXPECT_FALSE( - RFindInReadable(NS_LITERAL_CSTRING("gecko"), delim_begin, delim_end)); + EXPECT_FALSE(RFindInReadable("gecko"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -785,8 +776,7 @@ TEST_F(Strings, rfindinreadable) { delim_begin = begin; for (int i = 0; i < 6; i++) delim_begin++; delim_end = end; - EXPECT_FALSE( - RFindInReadable(NS_LITERAL_CSTRING("jar:"), delim_begin, delim_end)); + EXPECT_FALSE(RFindInReadable("jar:"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -795,8 +785,7 @@ TEST_F(Strings, rfindinreadable) { delim_begin = begin; delim_end = end; for (int i = 0; i < 7; i++) delim_end--; - EXPECT_FALSE( - RFindInReadable(NS_LITERAL_CSTRING("classic"), delim_begin, delim_end)); + EXPECT_FALSE(RFindInReadable("classic"_ns, delim_begin, delim_end)); // When no match is found, range should be empty EXPECT_EQ(delim_begin, delim_end); @@ -967,8 +956,8 @@ TEST_F(Strings, concat) { nsCString bar("bar"); const nsACString& barRef = bar; - const nsPromiseFlatCString& result = PromiseFlatCString( - NS_LITERAL_CSTRING("foo") + NS_LITERAL_CSTRING(",") + barRef); + const nsPromiseFlatCString& result = + PromiseFlatCString("foo"_ns + ","_ns + barRef); EXPECT_STREQ(result.get(), "foo,bar"); } @@ -1330,13 +1319,12 @@ static void test_strip_chars_helper(const char16_t* str, const char16_t* strip, TEST(String, strip_chars) { - test_strip_chars_helper(u"foo \r \nbar", u" \n\r", - NS_LITERAL_STRING("foobar")); - test_strip_chars_helper(u"\r\nfoo\r\n", u" \n\r", NS_LITERAL_STRING("foo")); - test_strip_chars_helper(u"foo", u" \n\r", NS_LITERAL_STRING("foo")); - test_strip_chars_helper(u"foo", u"fo", NS_LITERAL_STRING("")); - test_strip_chars_helper(u"foo", u"foo", NS_LITERAL_STRING("")); - test_strip_chars_helper(u" foo", u" ", NS_LITERAL_STRING("foo")); + test_strip_chars_helper(u"foo \r \nbar", u" \n\r", u"foobar"_ns); + test_strip_chars_helper(u"\r\nfoo\r\n", u" \n\r", u"foo"_ns); + test_strip_chars_helper(u"foo", u" \n\r", u"foo"_ns); + test_strip_chars_helper(u"foo", u"fo", u""_ns); + test_strip_chars_helper(u"foo", u"foo", u""_ns); + test_strip_chars_helper(u" foo", u" ", u"foo"_ns); } TEST_F(Strings, append_with_capacity) { @@ -1543,20 +1531,19 @@ static void test_tofloat_helper(const nsString& aStr, float aExpected, } TEST_F(Strings, tofloat) { - test_tofloat_helper(NS_LITERAL_STRING("42"), 42.f, true); - test_tofloat_helper(NS_LITERAL_STRING("42.0"), 42.f, true); - test_tofloat_helper(NS_LITERAL_STRING("-42"), -42.f, true); - test_tofloat_helper(NS_LITERAL_STRING("+42"), 42, true); - test_tofloat_helper(NS_LITERAL_STRING("13.37"), 13.37f, true); - test_tofloat_helper(NS_LITERAL_STRING("1.23456789"), 1.23456789f, true); - test_tofloat_helper(NS_LITERAL_STRING("1.98765432123456"), 1.98765432123456f, - true); - test_tofloat_helper(NS_LITERAL_STRING("0"), 0.f, true); - test_tofloat_helper(NS_LITERAL_STRING("1.e5"), 100000, true); - test_tofloat_helper(NS_LITERAL_STRING(""), 0.f, false); - test_tofloat_helper(NS_LITERAL_STRING("42foo"), 42.f, false); - test_tofloat_helper(NS_LITERAL_STRING("foo"), 0.f, false); - test_tofloat_helper(NS_LITERAL_STRING("1.5e-"), 1.5f, false); + test_tofloat_helper(u"42"_ns, 42.f, true); + test_tofloat_helper(u"42.0"_ns, 42.f, true); + test_tofloat_helper(u"-42"_ns, -42.f, true); + test_tofloat_helper(u"+42"_ns, 42, true); + test_tofloat_helper(u"13.37"_ns, 13.37f, true); + test_tofloat_helper(u"1.23456789"_ns, 1.23456789f, true); + test_tofloat_helper(u"1.98765432123456"_ns, 1.98765432123456f, true); + test_tofloat_helper(u"0"_ns, 0.f, true); + test_tofloat_helper(u"1.e5"_ns, 100000, true); + test_tofloat_helper(u""_ns, 0.f, false); + test_tofloat_helper(u"42foo"_ns, 42.f, false); + test_tofloat_helper(u"foo"_ns, 0.f, false); + test_tofloat_helper(u"1.5e-"_ns, 1.5f, false); } static void test_tofloat_allow_trailing_chars_helper(const nsString& aStr, @@ -1572,17 +1559,12 @@ static void test_tofloat_allow_trailing_chars_helper(const nsString& aStr, } TEST_F(Strings, ToFloatAllowTrailingChars) { - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING(""), 0.f, false); - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING("foo"), 0.f, - false); - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING("42foo"), 42.f, - true); - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING("42-5"), 42.f, - true); - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING("13.37.8"), 13.37f, - true); - test_tofloat_allow_trailing_chars_helper(NS_LITERAL_STRING("1.5e-"), 1.5f, - true); + test_tofloat_allow_trailing_chars_helper(u""_ns, 0.f, false); + test_tofloat_allow_trailing_chars_helper(u"foo"_ns, 0.f, false); + test_tofloat_allow_trailing_chars_helper(u"42foo"_ns, 42.f, true); + test_tofloat_allow_trailing_chars_helper(u"42-5"_ns, 42.f, true); + test_tofloat_allow_trailing_chars_helper(u"13.37.8"_ns, 13.37f, true); + test_tofloat_allow_trailing_chars_helper(u"1.5e-"_ns, 1.5f, true); } static void test_todouble_helper(const nsString& aStr, double aExpected, @@ -1597,22 +1579,21 @@ static void test_todouble_helper(const nsString& aStr, double aExpected, } TEST_F(Strings, todouble) { - test_todouble_helper(NS_LITERAL_STRING("42"), 42, true); - test_todouble_helper(NS_LITERAL_STRING("42.0"), 42, true); - test_todouble_helper(NS_LITERAL_STRING("-42"), -42, true); - test_todouble_helper(NS_LITERAL_STRING("+42"), 42, true); - test_todouble_helper(NS_LITERAL_STRING("13.37"), 13.37, true); - test_todouble_helper(NS_LITERAL_STRING("1.23456789"), 1.23456789, true); - test_todouble_helper(NS_LITERAL_STRING("1.98765432123456"), 1.98765432123456, + test_todouble_helper(u"42"_ns, 42, true); + test_todouble_helper(u"42.0"_ns, 42, true); + test_todouble_helper(u"-42"_ns, -42, true); + test_todouble_helper(u"+42"_ns, 42, true); + test_todouble_helper(u"13.37"_ns, 13.37, true); + test_todouble_helper(u"1.23456789"_ns, 1.23456789, true); + test_todouble_helper(u"1.98765432123456"_ns, 1.98765432123456, true); + test_todouble_helper(u"123456789.98765432123456"_ns, 123456789.98765432123456, true); - test_todouble_helper(NS_LITERAL_STRING("123456789.98765432123456"), - 123456789.98765432123456, true); - test_todouble_helper(NS_LITERAL_STRING("0"), 0, true); - test_todouble_helper(NS_LITERAL_STRING("1.e5"), 100000, true); - test_todouble_helper(NS_LITERAL_STRING(""), 0, false); - test_todouble_helper(NS_LITERAL_STRING("42foo"), 42, false); - test_todouble_helper(NS_LITERAL_STRING("foo"), 0, false); - test_todouble_helper(NS_LITERAL_STRING("1.5e-"), 1.5, false); + test_todouble_helper(u"0"_ns, 0, true); + test_todouble_helper(u"1.e5"_ns, 100000, true); + test_todouble_helper(u""_ns, 0, false); + test_todouble_helper(u"42foo"_ns, 42, false); + test_todouble_helper(u"foo"_ns, 0, false); + test_todouble_helper(u"1.5e-"_ns, 1.5, false); } static void test_todouble_allow_trailing_chars_helper(const nsString& aStr, @@ -1628,16 +1609,12 @@ static void test_todouble_allow_trailing_chars_helper(const nsString& aStr, } TEST_F(Strings, ToDoubleAllowTrailingChars) { - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING(""), 0, false); - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING("foo"), 0, false); - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING("42foo"), 42, - true); - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING("42-5"), 42, - true); - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING("13.37.8"), 13.37, - true); - test_todouble_allow_trailing_chars_helper(NS_LITERAL_STRING("1.5e-"), 1.5, - true); + test_todouble_allow_trailing_chars_helper(u""_ns, 0, false); + test_todouble_allow_trailing_chars_helper(u"foo"_ns, 0, false); + test_todouble_allow_trailing_chars_helper(u"42foo"_ns, 42, true); + test_todouble_allow_trailing_chars_helper(u"42-5"_ns, 42, true); + test_todouble_allow_trailing_chars_helper(u"13.37.8"_ns, 13.37, true); + test_todouble_allow_trailing_chars_helper(u"1.5e-"_ns, 1.5, true); } TEST_F(Strings, Split) { @@ -1709,9 +1686,9 @@ TEST_F(Strings, Split) { counter = 0; for (const nsAString& token : wide.Split(' ')) { if (counter == 0) { - EXPECT_TRUE(token.Equals(NS_LITERAL_STRING("hello"))); + EXPECT_TRUE(token.Equals(u"hello"_ns)); } else if (counter == 1) { - EXPECT_TRUE(token.Equals(NS_LITERAL_STRING("world"))); + EXPECT_TRUE(token.Equals(u"world"_ns)); } counter++; } @@ -2484,7 +2461,7 @@ CONVERSION_BENCH(PerfUTF8toUTF16VIThousand, CopyUTF8toUTF16, mViThousandUtf8, nsAutoString); // Tests for usability of nsTLiteralString in constant expressions. -static_assert(NS_LITERAL_STRING("").IsEmpty()); +static_assert(u""_ns.IsEmpty()); constexpr auto testStringA = NS_LITERAL_STRING("a"); static_assert(!testStringA.IsEmpty()); diff --git a/xpcom/tests/gtest/TestSubstringTuple.cpp b/xpcom/tests/gtest/TestSubstringTuple.cpp index e6a6e9bea8f1..4a84ad9a8e51 100644 --- a/xpcom/tests/gtest/TestSubstringTuple.cpp +++ b/xpcom/tests/gtest/TestSubstringTuple.cpp @@ -9,7 +9,7 @@ namespace TestSubstringTuple { -static const auto kFooLiteral = NS_LITERAL_STRING("foo"); +static const auto kFooLiteral = u"foo"_ns; static const auto kFoo = nsCString("foo"); static const auto kBar = nsCString("bar"); @@ -33,16 +33,10 @@ static const auto kBaz = nsCString("baz"); EXPECT_EQ(isDependentOn, combinedIsDependentOn); TEST(SubstringTuple, IsDependentOnAndLength_NonDependent_Literal_ZeroLength) -{ - DO_SUBSTRING_TUPLE_TEST(NS_LITERAL_STRING("") + NS_LITERAL_STRING(""), - kFooLiteral, 0u, false); -} +{ DO_SUBSTRING_TUPLE_TEST(u""_ns + u""_ns, kFooLiteral, 0u, false); } TEST(SubstringTuple, IsDependentOnAndLength_NonDependent_Literal_NonZeroLength) -{ - DO_SUBSTRING_TUPLE_TEST(NS_LITERAL_STRING("bar") + NS_LITERAL_STRING("baz"), - kFooLiteral, 6u, false); -} +{ DO_SUBSTRING_TUPLE_TEST(u"bar"_ns + u"baz"_ns, kFooLiteral, 6u, false); } TEST(SubstringTuple, IsDependentOnAndLength_NonDependent_NonZeroLength) { DO_SUBSTRING_TUPLE_TEST(kBar + kBaz, kFoo, 6u, false); } diff --git a/xpcom/tests/gtest/TestTextFormatter.cpp b/xpcom/tests/gtest/TestTextFormatter.cpp index 0c2e35dc1e7e..1109a890a994 100644 --- a/xpcom/tests/gtest/TestTextFormatter.cpp +++ b/xpcom/tests/gtest/TestTextFormatter.cpp @@ -9,7 +9,7 @@ TEST(TextFormatter, Tests) { - nsAutoString fmt(NS_LITERAL_STRING("%3$s %4$S %1$d %2$d %2$d %3$s")); + nsAutoString fmt(u"%3$s %4$S %1$d %2$d %2$d %3$s"_ns); char utf8[] = "Hello"; char16_t ucs2[] = {'W', 'o', 'r', 'l', 'd', 0x4e00, 0xAc00, 0xFF45, 0x0103, 0x00}; diff --git a/xpcom/tests/gtest/TestThreadMetrics.cpp b/xpcom/tests/gtest/TestThreadMetrics.cpp index 0b1b12a56317..d7686d9eb000 100644 --- a/xpcom/tests/gtest/TestThreadMetrics.cpp +++ b/xpcom/tests/gtest/TestThreadMetrics.cpp @@ -120,8 +120,8 @@ class ThreadMetrics : public ::testing::Test { // building the DocGroup structure RefPtr group = dom::BrowsingContextGroup::Create(); - mDocGroup = group->AddDocument(NS_LITERAL_CSTRING("key"), nullptr); - mDocGroup2 = group->AddDocument(NS_LITERAL_CSTRING("key2"), nullptr); + mDocGroup = group->AddDocument("key"_ns, nullptr); + mDocGroup2 = group->AddDocument("key2"_ns, nullptr); mCounter = mDocGroup->GetPerformanceCounter(); mCounter2 = mDocGroup2->GetPerformanceCounter(); mThreadMgr = do_GetService("@mozilla.org/thread-manager;1"); diff --git a/xpcom/tests/gtest/TestTokenizer.cpp b/xpcom/tests/gtest/TestTokenizer.cpp index 40032c392ecc..45b133d42918 100644 --- a/xpcom/tests/gtest/TestTokenizer.cpp +++ b/xpcom/tests/gtest/TestTokenizer.cpp @@ -28,11 +28,11 @@ TEST(Tokenizer, HTTPResponse) // Real life test, HTTP response Tokenizer p( - NS_LITERAL_CSTRING("HTTP/1.0 304 Not modified\r\n" - "ETag: hallo\r\n" - "Content-Length: 16\r\n" - "\r\n" - "This is the body")); + nsLiteralCString("HTTP/1.0 304 Not modified\r\n" + "ETag: hallo\r\n" + "Content-Length: 16\r\n" + "\r\n" + "This is the body")); EXPECT_TRUE(p.CheckWord("HTTP")); EXPECT_TRUE(p.CheckChar('/')); @@ -101,7 +101,7 @@ TEST(Tokenizer, Main) // Synthetic code-specific test - Tokenizer p(NS_LITERAL_CSTRING("test123 ,15 \t*\r\n%xx,-15\r\r")); + Tokenizer p("test123 ,15 \t*\r\n%xx,-15\r\r"_ns); EXPECT_TRUE(p.Next(t)); EXPECT_TRUE(t.Type() == Tokenizer::TOKEN_WORD); @@ -215,11 +215,11 @@ TEST(Tokenizer, Main16) // Synthetic code-specific test - Tokenizer16 p(NS_LITERAL_STRING("test123 ,15 \t*\r\n%xx,-15\r\r")); + Tokenizer16 p(u"test123 ,15 \t*\r\n%xx,-15\r\r"_ns); EXPECT_TRUE(p.Next(t)); EXPECT_TRUE(t.Type() == Tokenizer16::TOKEN_WORD); - EXPECT_TRUE(t.AsString() == NS_LITERAL_STRING("test123")); + EXPECT_TRUE(t.AsString() == u"test123"_ns); Tokenizer16::Token u; EXPECT_FALSE(p.Check(u)); @@ -274,21 +274,21 @@ TEST(Tokenizer, Main16) nsAutoString claim; p.Claim(claim, Tokenizer16::EXCLUDE_LAST); - EXPECT_TRUE(claim == NS_LITERAL_STRING("*\r\n")); + EXPECT_TRUE(claim == u"*\r\n"_ns); p.Claim(claim, Tokenizer16::INCLUDE_LAST); - EXPECT_TRUE(claim == NS_LITERAL_STRING("*\r\n%")); + EXPECT_TRUE(claim == u"*\r\n%"_ns); p.Rollback(); EXPECT_TRUE(p.CheckChar('%')); p.Record(Tokenizer16::INCLUDE_LAST); - EXPECT_FALSE(p.CheckWord(NS_LITERAL_STRING("xy"))); + EXPECT_FALSE(p.CheckWord(u"xy"_ns)); - EXPECT_TRUE(p.CheckWord(NS_LITERAL_STRING("xx"))); + EXPECT_TRUE(p.CheckWord(u"xx"_ns)); p.Claim(claim, Tokenizer16::INCLUDE_LAST); - EXPECT_TRUE(claim == NS_LITERAL_STRING("%xx")); + EXPECT_TRUE(claim == u"%xx"_ns); EXPECT_TRUE(p.Next(t)); EXPECT_TRUE(t.Type() == Tokenizer16::TOKEN_CHAR); @@ -327,7 +327,7 @@ TEST(Tokenizer, SingleWord) { // Single word with numbers in it test - Tokenizer p(NS_LITERAL_CSTRING("test123")); + Tokenizer p("test123"_ns); EXPECT_TRUE(p.CheckWord("test123")); EXPECT_TRUE(p.CheckEOF()); @@ -337,7 +337,7 @@ TEST(Tokenizer, EndingAfterNumber) { // An end handling after a number - Tokenizer p(NS_LITERAL_CSTRING("123")); + Tokenizer p("123"_ns); EXPECT_FALSE(p.CheckWord("123")); EXPECT_TRUE(p.Check(Tokenizer::Token::Number(123))); @@ -350,7 +350,7 @@ TEST(Tokenizer, BadInteger) // A bad integer test - Tokenizer p(NS_LITERAL_CSTRING("189234891274981758617846178651647620587135")); + Tokenizer p("189234891274981758617846178651647620587135"_ns); EXPECT_TRUE(p.Next(t)); EXPECT_TRUE(t.Type() == Tokenizer::TOKEN_ERROR); @@ -363,7 +363,7 @@ TEST(Tokenizer, CheckExpectedTokenValue) // Check expected token value test - Tokenizer p(NS_LITERAL_CSTRING("blue velvet")); + Tokenizer p("blue velvet"_ns); EXPECT_FALSE(p.Check(Tokenizer::TOKEN_INTEGER, t)); @@ -388,13 +388,13 @@ TEST(Tokenizer, HasFailed) // HasFailed test - Tokenizer p1(NS_LITERAL_CSTRING("a b")); + Tokenizer p1("a b"_ns); while (p1.Next(t) && t.Type() != Tokenizer::TOKEN_CHAR) ; EXPECT_TRUE(p1.HasFailed()); - Tokenizer p2(NS_LITERAL_CSTRING("a b ?!c")); + Tokenizer p2("a b ?!c"_ns); EXPECT_FALSE(p2.CheckChar('c')); EXPECT_TRUE(p2.HasFailed()); @@ -462,7 +462,7 @@ TEST(Tokenizer, Construction) } { - Tokenizer p1(NS_LITERAL_CSTRING("test")); + Tokenizer p1("test"_ns); EXPECT_TRUE(p1.CheckWord("test")); EXPECT_TRUE(p1.CheckEOF()); } @@ -476,15 +476,14 @@ TEST(Tokenizer, Construction) TEST(Tokenizer, Customization) { - Tokenizer p1(NS_LITERAL_CSTRING("test-custom*words and\tdefault-whites"), - nullptr, "-*"); + Tokenizer p1("test-custom*words and\tdefault-whites"_ns, nullptr, "-*"); EXPECT_TRUE(p1.CheckWord("test-custom*words")); EXPECT_TRUE(p1.CheckWhite()); EXPECT_TRUE(p1.CheckWord("and")); EXPECT_TRUE(p1.CheckWhite()); EXPECT_TRUE(p1.CheckWord("default-whites")); - Tokenizer p2(NS_LITERAL_CSTRING("test, custom,whites"), ", "); + Tokenizer p2("test, custom,whites"_ns, ", "); EXPECT_TRUE(p2.CheckWord("test")); EXPECT_TRUE(p2.CheckWhite()); EXPECT_TRUE(p2.CheckWhite()); @@ -492,8 +491,7 @@ TEST(Tokenizer, Customization) EXPECT_TRUE(p2.CheckWhite()); EXPECT_TRUE(p2.CheckWord("whites")); - Tokenizer p3(NS_LITERAL_CSTRING("test, custom, whites-and#word-chars"), ",", - "-#"); + Tokenizer p3("test, custom, whites-and#word-chars"_ns, ",", "-#"); EXPECT_TRUE(p3.CheckWord("test")); EXPECT_TRUE(p3.CheckWhite()); EXPECT_FALSE(p3.CheckWhite()); @@ -789,12 +787,11 @@ TEST(Tokenizer, ReadUntil) EXPECT_TRUE(f == "Hello;test 4,"); p.Rollback(); - EXPECT_TRUE( - p.ReadUntil(Tokenizer::Token::Word(NS_LITERAL_CSTRING("test")), f)); + EXPECT_TRUE(p.ReadUntil(Tokenizer::Token::Word("test"_ns), f)); EXPECT_TRUE(f == "Hello;"); p.Rollback(); - EXPECT_TRUE(p.ReadUntil(Tokenizer::Token::Word(NS_LITERAL_CSTRING("test")), f, + EXPECT_TRUE(p.ReadUntil(Tokenizer::Token::Word("test"_ns), f, Tokenizer::INCLUDE_LAST)); EXPECT_TRUE(f == "Hello;test"); EXPECT_TRUE(p.ReadUntil(Tokenizer::Token::Char(','), f)); @@ -949,13 +946,13 @@ TEST(Tokenizer, Incremental) [&](Token const& t, IncrementalTokenizer& i) -> nsresult { switch (++test) { case 1: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test1")))); + EXPECT_TRUE(t.Equals(Token::Word("test1"_ns))); break; case 2: EXPECT_TRUE(t.Equals(Token::Char(','))); break; case 3: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test2")))); + EXPECT_TRUE(t.Equals(Token::Word("test2"_ns))); break; case 4: EXPECT_TRUE(t.Equals(Token::Char(','))); @@ -967,7 +964,7 @@ TEST(Tokenizer, Incremental) EXPECT_TRUE(t.Equals(Token::Char(','))); break; case 7: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test3")))); + EXPECT_TRUE(t.Equals(Token::Word("test3"_ns))); break; case 8: EXPECT_TRUE(t.Equals(Token::EndOfFile())); @@ -998,17 +995,17 @@ TEST(Tokenizer, IncrementalRollback) [&](Token const& t, IncrementalTokenizer& i) -> nsresult { switch (++test) { case 1: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test1")))); + EXPECT_TRUE(t.Equals(Token::Word("test1"_ns))); break; case 2: EXPECT_TRUE(t.Equals(Token::Char(','))); break; case 3: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test2")))); + EXPECT_TRUE(t.Equals(Token::Word("test2"_ns))); i.Rollback(); // so that we get the token again break; case 4: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test2")))); + EXPECT_TRUE(t.Equals(Token::Word("test2"_ns))); break; case 5: EXPECT_TRUE(t.Equals(Token::Char(','))); @@ -1020,7 +1017,7 @@ TEST(Tokenizer, IncrementalRollback) EXPECT_TRUE(t.Equals(Token::Char(','))); break; case 8: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("test3")))); + EXPECT_TRUE(t.Equals(Token::Word("test3"_ns))); break; case 9: EXPECT_TRUE(t.Equals(Token::EndOfFile())); @@ -1052,7 +1049,7 @@ TEST(Tokenizer, IncrementalNeedMoreInput) Token t2; switch (++test) { case 1: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("a")))); + EXPECT_TRUE(t.Equals(Token::Word("a"_ns))); break; case 2: case 3: @@ -1061,7 +1058,7 @@ TEST(Tokenizer, IncrementalNeedMoreInput) EXPECT_TRUE(t.Equals(Token::Whitespace())); if (i.Next(t2)) { EXPECT_TRUE(test == 5); - EXPECT_TRUE(t2.Equals(Token::Word(NS_LITERAL_CSTRING("bb")))); + EXPECT_TRUE(t2.Equals(Token::Word("bb"_ns))); } else { EXPECT_TRUE(test < 5); i.NeedMoreInput(); @@ -1071,7 +1068,7 @@ TEST(Tokenizer, IncrementalNeedMoreInput) EXPECT_TRUE(t.Equals(Token::Char(','))); break; case 7: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("c")))); + EXPECT_TRUE(t.Equals(Token::Word("c"_ns))); return NS_ERROR_FAILURE; default: EXPECT_TRUE(false); @@ -1114,7 +1111,7 @@ TEST(Tokenizer, IncrementalCustom) EXPECT_TRUE(t.Equals(custom)); break; case 2: - EXPECT_TRUE(t.Equals(Token::Word(NS_LITERAL_CSTRING("bla")))); + EXPECT_TRUE(t.Equals(Token::Word("bla"_ns))); break; case 3: EXPECT_TRUE(t.Equals(Token::EndOfFile())); @@ -1126,11 +1123,11 @@ TEST(Tokenizer, IncrementalCustom) nullptr, "-"); custom = i.AddCustomToken("some-test", Tokenizer::CASE_SENSITIVE); - i.FeedInput(NS_LITERAL_CSTRING("some-")); + i.FeedInput("some-"_ns); EXPECT_TRUE(test == 0); - i.FeedInput(NS_LITERAL_CSTRING("tes")); + i.FeedInput("tes"_ns); EXPECT_TRUE(test == 0); - i.FeedInput(NS_LITERAL_CSTRING("tbla")); + i.FeedInput("tbla"_ns); EXPECT_TRUE(test == 1); i.FinishInput(); EXPECT_TRUE(test == 3); @@ -1267,17 +1264,17 @@ TEST(Tokenizer, IncrementalBuffering1) Unused << i.AddCustomToken("bb", Tokenizer::CASE_SENSITIVE); i.SetTokenizingMode(Tokenizer::Mode::CUSTOM_ONLY); - i.FeedInput(NS_LITERAL_CSTRING("01234")); + i.FeedInput("01234"_ns); EXPECT_TRUE(test == 1); EXPECT_TRUE(observedFragment.EqualsLiteral("012")); - i.FeedInput(NS_LITERAL_CSTRING("5")); + i.FeedInput("5"_ns); EXPECT_TRUE(test == 1); - i.FeedInput(NS_LITERAL_CSTRING("6789aa")); + i.FeedInput("6789aa"_ns); EXPECT_TRUE(test == 2); EXPECT_TRUE(observedFragment.EqualsLiteral("3456789")); - i.FeedInput(NS_LITERAL_CSTRING("aqwert")); + i.FeedInput("aqwert"_ns); EXPECT_TRUE(test == 4); EXPECT_TRUE(observedFragment.EqualsLiteral("qwe")); @@ -1323,13 +1320,13 @@ TEST(Tokenizer, IncrementalBuffering2) Unused << i.AddCustomToken("bbbbb", Tokenizer::CASE_SENSITIVE); i.SetTokenizingMode(Tokenizer::Mode::CUSTOM_ONLY); - i.FeedInput(NS_LITERAL_CSTRING("01234")); + i.FeedInput("01234"_ns); EXPECT_TRUE(test == 0); - i.FeedInput(NS_LITERAL_CSTRING("5")); + i.FeedInput("5"_ns); EXPECT_TRUE(test == 1); - i.FeedInput(NS_LITERAL_CSTRING("6789aa")); + i.FeedInput("6789aa"_ns); EXPECT_TRUE(test == 2); - i.FeedInput(NS_LITERAL_CSTRING("aqwert")); + i.FeedInput("aqwert"_ns); EXPECT_TRUE(test == 4); i.FinishInput(); EXPECT_TRUE(test == 6); diff --git a/xpcom/tests/gtest/TestUTF.cpp b/xpcom/tests/gtest/TestUTF.cpp index ec5f2b555e01..cb574aa8553f 100644 --- a/xpcom/tests/gtest/TestUTF.cpp +++ b/xpcom/tests/gtest/TestUTF.cpp @@ -34,11 +34,11 @@ TEST(UTF, Valid) nsCString tmp8("string "); AppendUTF16toUTF8(str16, tmp8); - EXPECT_TRUE(tmp8.Equals(NS_LITERAL_CSTRING("string ") + str8)); + EXPECT_TRUE(tmp8.Equals("string "_ns + str8)); - nsString tmp16(NS_LITERAL_STRING("string ")); + nsString tmp16(u"string "_ns); AppendUTF8toUTF16(str8, tmp16); - EXPECT_TRUE(tmp16.Equals(NS_LITERAL_STRING("string ") + str16)); + EXPECT_TRUE(tmp16.Equals(u"string "_ns + str16)); EXPECT_EQ(CompareUTF8toUTF16(str8, str16), 0); } @@ -54,7 +54,7 @@ TEST(UTF, Invalid16) nsCString tmp8("string "); AppendUTF16toUTF8(str16, tmp8); - EXPECT_TRUE(tmp8.Equals(NS_LITERAL_CSTRING("string ") + str8)); + EXPECT_TRUE(tmp8.Equals("string "_ns + str8)); EXPECT_EQ(CompareUTF8toUTF16(str8, str16), 0); } @@ -68,9 +68,9 @@ TEST(UTF, Invalid8) EXPECT_TRUE(NS_ConvertUTF8toUTF16(str8).Equals(str16)); - nsString tmp16(NS_LITERAL_STRING("string ")); + nsString tmp16(u"string "_ns); AppendUTF8toUTF16(str8, tmp16); - EXPECT_TRUE(tmp16.Equals(NS_LITERAL_STRING("string ") + str16)); + EXPECT_TRUE(tmp16.Equals(u"string "_ns + str16)); EXPECT_EQ(CompareUTF8toUTF16(str8, str16), 0); } @@ -84,9 +84,9 @@ TEST(UTF, Malformed8) EXPECT_TRUE(NS_ConvertUTF8toUTF16(str8).Equals(str16)); - nsString tmp16(NS_LITERAL_STRING("string ")); + nsString tmp16(u"string "_ns); AppendUTF8toUTF16(str8, tmp16); - EXPECT_TRUE(tmp16.Equals(NS_LITERAL_STRING("string ") + str16)); + EXPECT_TRUE(tmp16.Equals(u"string "_ns + str16)); EXPECT_EQ(CompareUTF8toUTF16(str8, str16), 0); } diff --git a/xpcom/tests/windows/TestNtPathToDosPath.cpp b/xpcom/tests/windows/TestNtPathToDosPath.cpp index e8e0fea2010d..ac29ddac5049 100644 --- a/xpcom/tests/windows/TestNtPathToDosPath.cpp +++ b/xpcom/tests/windows/TestNtPathToDosPath.cpp @@ -151,7 +151,7 @@ TEST(NtPathToDosPath, Tests) EXPECT_TRUE(TestNtPathToDosPath(L"\\Device\\LanmanRedirector\\127.0.0.1\\C$", L"\\\\127.0.0.1\\C$")); - DriveMapping drvMapping(NS_LITERAL_STRING("\\\\127.0.0.1\\C$")); + DriveMapping drvMapping(u"\\\\127.0.0.1\\C$"_ns); // Only run these tests if we were able to map; some machines don't have perms if (drvMapping.Init()) { wchar_t expected[] = L" :\\"; diff --git a/xpcom/threads/CPUUsageWatcher.cpp b/xpcom/threads/CPUUsageWatcher.cpp index 68f8662bbce2..ba11557eecb8 100644 --- a/xpcom/threads/CPUUsageWatcher.cpp +++ b/xpcom/threads/CPUUsageWatcher.cpp @@ -231,7 +231,7 @@ void CPUUsageWatcher::AnnotateHang(BackgroundHangAnnotations& aAnnotations) { } if (mExternalUsageRatio > mExternalUsageThreshold) { - aAnnotations.AddAnnotation(NS_LITERAL_STRING("ExternalCPUHigh"), true); + aAnnotations.AddAnnotation(u"ExternalCPUHigh"_ns, true); } } diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index ad4a694602fe..1c86c8298b28 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -71,7 +71,7 @@ nsresult BackgroundEventTarget::Init() { nsCOMPtr pool(new nsThreadPool()); NS_ENSURE_TRUE(pool, NS_ERROR_FAILURE); - nsresult rv = pool->SetName(NS_LITERAL_CSTRING("BackgroundThreadPool")); + nsresult rv = pool->SetName("BackgroundThreadPool"_ns); NS_ENSURE_SUCCESS(rv, rv); // Use potentially more conservative stack size. @@ -90,7 +90,7 @@ nsresult BackgroundEventTarget::Init() { nsCOMPtr ioPool(new nsThreadPool()); NS_ENSURE_TRUE(pool, NS_ERROR_FAILURE); - rv = ioPool->SetName(NS_LITERAL_CSTRING("BgIOThreadPool")); + rv = ioPool->SetName("BgIOThreadPool"_ns); NS_ENSURE_SUCCESS(rv, rv); // Use potentially more conservative stack size. @@ -602,7 +602,7 @@ bool nsThreadManager::IsNSThread() const { NS_IMETHODIMP nsThreadManager::NewThread(uint32_t aCreationFlags, uint32_t aStackSize, nsIThread** aResult) { - return NewNamedThread(NS_LITERAL_CSTRING(""), aStackSize, aResult); + return NewNamedThread(""_ns, aStackSize, aResult); } NS_IMETHODIMP diff --git a/xpfe/appshell/AppWindow.cpp b/xpfe/appshell/AppWindow.cpp index c045e4aa9495..c17b2f7b4e8c 100644 --- a/xpfe/appshell/AppWindow.cpp +++ b/xpfe/appshell/AppWindow.cpp @@ -72,21 +72,21 @@ # define USE_NATIVE_MENUS #endif -#define SIZEMODE_NORMAL NS_LITERAL_STRING("normal") -#define SIZEMODE_MAXIMIZED NS_LITERAL_STRING("maximized") -#define SIZEMODE_MINIMIZED NS_LITERAL_STRING("minimized") -#define SIZEMODE_FULLSCREEN NS_LITERAL_STRING("fullscreen") - -#define WINDOWTYPE_ATTRIBUTE NS_LITERAL_STRING("windowtype") - -#define PERSIST_ATTRIBUTE NS_LITERAL_STRING("persist") -#define SCREENX_ATTRIBUTE NS_LITERAL_STRING("screenX") -#define SCREENY_ATTRIBUTE NS_LITERAL_STRING("screenY") -#define WIDTH_ATTRIBUTE NS_LITERAL_STRING("width") -#define HEIGHT_ATTRIBUTE NS_LITERAL_STRING("height") -#define MODE_ATTRIBUTE NS_LITERAL_STRING("sizemode") -#define TILED_ATTRIBUTE NS_LITERAL_STRING("gtktiledwindow") -#define ZLEVEL_ATTRIBUTE NS_LITERAL_STRING("zlevel") +#define SIZEMODE_NORMAL u"normal"_ns +#define SIZEMODE_MAXIMIZED u"maximized"_ns +#define SIZEMODE_MINIMIZED u"minimized"_ns +#define SIZEMODE_FULLSCREEN u"fullscreen"_ns + +#define WINDOWTYPE_ATTRIBUTE u"windowtype"_ns + +#define PERSIST_ATTRIBUTE u"persist"_ns +#define SCREENX_ATTRIBUTE u"screenX"_ns +#define SCREENY_ATTRIBUTE u"screenY"_ns +#define WIDTH_ATTRIBUTE u"width"_ns +#define HEIGHT_ATTRIBUTE u"height"_ns +#define MODE_ATTRIBUTE u"sizemode"_ns +#define TILED_ATTRIBUTE u"gtktiledwindow"_ns +#define ZLEVEL_ATTRIBUTE u"zlevel"_ns #define SIZE_PERSISTENCE_TIMEOUT 500 // msec @@ -357,10 +357,10 @@ NS_IMETHODIMP AppWindow::SetZLevel(uint32_t aLevel) { RefPtr doc = cv->GetDocument(); if (doc) { ErrorResult rv; - RefPtr event = doc->CreateEvent(NS_LITERAL_STRING("Events"), - dom::CallerType::System, rv); + RefPtr event = + doc->CreateEvent(u"Events"_ns, dom::CallerType::System, rv); if (event) { - event->InitEvent(NS_LITERAL_STRING("windowZLevel"), true, false); + event->InitEvent(u"windowZLevel"_ns, true, false); event->SetTrusted(true); @@ -1631,7 +1631,7 @@ void AppWindow::SyncAttributesToWidget() { // "chromemargin" attribute nsIntMargin margins; - windowElement->GetAttribute(NS_LITERAL_STRING("chromemargin"), attr); + windowElement->GetAttribute(u"chromemargin"_ns, attr); if (nsContentUtils::ParseIntMarginValue(attr, margins)) { LayoutDeviceIntMargin tmp = LayoutDeviceIntMargin::FromUnknownMargin(margins); @@ -1649,7 +1649,7 @@ void AppWindow::SyncAttributesToWidget() { NS_ENSURE_TRUE_VOID(mWindow); // "icon" attribute - windowElement->GetAttribute(NS_LITERAL_STRING("icon"), attr); + windowElement->GetAttribute(u"icon"_ns, attr); if (!attr.IsEmpty()) { mWindow->SetIcon(attr); @@ -1657,25 +1657,25 @@ void AppWindow::SyncAttributesToWidget() { } // "drawtitle" attribute - windowElement->GetAttribute(NS_LITERAL_STRING("drawtitle"), attr); + windowElement->GetAttribute(u"drawtitle"_ns, attr); mWindow->SetDrawsTitle(attr.LowerCaseEqualsLiteral("true")); NS_ENSURE_TRUE_VOID(mWindow); // "toggletoolbar" attribute - windowElement->GetAttribute(NS_LITERAL_STRING("toggletoolbar"), attr); + windowElement->GetAttribute(u"toggletoolbar"_ns, attr); mWindow->SetShowsToolbarButton(attr.LowerCaseEqualsLiteral("true")); NS_ENSURE_TRUE_VOID(mWindow); // "macnativefullscreen" attribute - windowElement->GetAttribute(NS_LITERAL_STRING("macnativefullscreen"), attr); + windowElement->GetAttribute(u"macnativefullscreen"_ns, attr); mWindow->SetSupportsNativeFullscreen(attr.LowerCaseEqualsLiteral("true")); NS_ENSURE_TRUE_VOID(mWindow); // "macanimationtype" attribute - windowElement->GetAttribute(NS_LITERAL_STRING("macanimationtype"), attr); + windowElement->GetAttribute(u"macanimationtype"_ns, attr); if (attr.EqualsLiteral("document")) { mWindow->SetWindowAnimationType(nsIWidget::eDocumentWindowAnimation); } @@ -1913,9 +1913,9 @@ NS_IMETHODIMP AppWindow::SavePersistentAttributes() { } bool tiled = mWindow->IsTiled(); if (tiled) { - sizeString.Assign(NS_LITERAL_STRING("true")); + sizeString.Assign(u"true"_ns); } else { - sizeString.Assign(NS_LITERAL_STRING("false")); + sizeString.Assign(u"false"_ns); } docShellElement->SetAttribute(TILED_ATTRIBUTE, sizeString, rv); if (persistString.Find("zlevel") >= 0) { @@ -2388,7 +2388,7 @@ void AppWindow::ApplyChromeFlags() { // Note that if we're not actually changing the value this will be a no-op, // so no need to compare to the old value. IgnoredErrorResult rv; - window->SetAttribute(NS_LITERAL_STRING("chromehidden"), newvalue, rv); + window->SetAttribute(u"chromehidden"_ns, newvalue, rv); } NS_IMETHODIMP @@ -2598,10 +2598,9 @@ bool AppWindow::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) { if (mDocShell && mDocShell->GetWindow()) { nsCOMPtr eventTarget = mDocShell->GetWindow()->GetTopWindowRoot(); - nsContentUtils::DispatchChromeEvent(mDocShell->GetDocument(), eventTarget, - NS_LITERAL_STRING("MozUpdateWindowPos"), - CanBubble::eNo, Cancelable::eNo, - nullptr); + nsContentUtils::DispatchChromeEvent( + mDocShell->GetDocument(), eventTarget, u"MozUpdateWindowPos"_ns, + CanBubble::eNo, Cancelable::eNo, nullptr); } // Persist position, but not immediately, in case this OS is firing @@ -2688,7 +2687,7 @@ void AppWindow::SizeModeChanged(nsSizeMode sizeMode) { } // And always fire a user-defined sizemodechange event on the window - ourWindow->DispatchCustomEvent(NS_LITERAL_STRING("sizemodechange")); + ourWindow->DispatchCustomEvent(u"sizemodechange"_ns); } if (PresShell* presShell = GetPresShell()) { @@ -2706,7 +2705,7 @@ void AppWindow::UIResolutionChanged() { nsCOMPtr ourWindow = mDocShell ? mDocShell->GetWindow() : nullptr; if (ourWindow) { - ourWindow->DispatchCustomEvent(NS_LITERAL_STRING("resolutionchange"), + ourWindow->DispatchCustomEvent(u"resolutionchange"_ns, ChromeOnlyDispatch::eYes); } } @@ -2732,7 +2731,7 @@ void AppWindow::OcclusionStateChanged(bool aIsFullyOccluded) { mDocShell ? mDocShell->GetWindow() : nullptr; if (ourWindow) { // And always fire a user-defined occlusionstatechange event on the window - ourWindow->DispatchCustomEvent(NS_LITERAL_STRING("occlusionstatechange"), + ourWindow->DispatchCustomEvent(u"occlusionstatechange"_ns, ChromeOnlyDispatch::eYes); } } @@ -2808,9 +2807,9 @@ static void LoadNativeMenus(Document* aDoc, nsIWidget* aParentWindow) { // Find the menubar tag (if there is more than one, we ignore all but // the first). nsCOMPtr menubarElements = aDoc->GetElementsByTagNameNS( - NS_LITERAL_STRING( - "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"), - NS_LITERAL_STRING("menubar")); + nsLiteralString( + u"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"), + u"menubar"_ns); nsCOMPtr menubarNode; if (menubarElements) { diff --git a/xpfe/appshell/nsAppShellWindowEnumerator.cpp b/xpfe/appshell/nsAppShellWindowEnumerator.cpp index 383f96d449a3..3e7a4fa4b8f2 100644 --- a/xpfe/appshell/nsAppShellWindowEnumerator.cpp +++ b/xpfe/appshell/nsAppShellWindowEnumerator.cpp @@ -54,7 +54,7 @@ void GetAttribute(nsIAppWindow* inWindow, const nsAString& inAttribute, // retrieve the window type, stored as the value of a particular // attribute in its XUL window tag void GetWindowType(nsIAppWindow* aWindow, nsString& outType) { - GetAttribute(aWindow, NS_LITERAL_STRING("windowtype"), outType); + GetAttribute(aWindow, u"windowtype"_ns, outType); } // diff --git a/xpfe/appshell/nsContentTreeOwner.cpp b/xpfe/appshell/nsContentTreeOwner.cpp index af534121f896..064154e30358 100644 --- a/xpfe/appshell/nsContentTreeOwner.cpp +++ b/xpfe/appshell/nsContentTreeOwner.cpp @@ -313,8 +313,7 @@ nsContentTreeOwner::SetPersistence(bool aPersistPosition, bool aPersistSize, ErrorResult rv; if (saveString) { - docShellElement->SetAttribute(NS_LITERAL_STRING("persist"), persistString, - rv); + docShellElement->SetAttribute(u"persist"_ns, persistString, rv); } return NS_OK;